How can I setup test data for functional testing in Grails?











up vote
0
down vote

favorite












So we have a restful service that we want to test using a restclient in grails.



The test code should go something like this...



class MyControllerSpec extends Specification {

def setup() {
this.dbEntity = new DbEntity("someid123").save();
}

void "Test entity GET"{
given:
RestBuilder rest = new RestBuilder()

when: "The DB entity service is hit"
RestResponse restResponse = rest.post("http://localhost:8080/api/someentity/$id");

then: "A 200 error is sent"
restResponse.status == 200


}


The problem I am having is the setup method blows up on .save() because there is not hibernate session. How can I manipulate my database before running a test?










share|improve this question






















  • Are you tried to add in test "setup:" block?
    – Koloritnij
    Dec 3 '15 at 9:33















up vote
0
down vote

favorite












So we have a restful service that we want to test using a restclient in grails.



The test code should go something like this...



class MyControllerSpec extends Specification {

def setup() {
this.dbEntity = new DbEntity("someid123").save();
}

void "Test entity GET"{
given:
RestBuilder rest = new RestBuilder()

when: "The DB entity service is hit"
RestResponse restResponse = rest.post("http://localhost:8080/api/someentity/$id");

then: "A 200 error is sent"
restResponse.status == 200


}


The problem I am having is the setup method blows up on .save() because there is not hibernate session. How can I manipulate my database before running a test?










share|improve this question






















  • Are you tried to add in test "setup:" block?
    – Koloritnij
    Dec 3 '15 at 9:33













up vote
0
down vote

favorite









up vote
0
down vote

favorite











So we have a restful service that we want to test using a restclient in grails.



The test code should go something like this...



class MyControllerSpec extends Specification {

def setup() {
this.dbEntity = new DbEntity("someid123").save();
}

void "Test entity GET"{
given:
RestBuilder rest = new RestBuilder()

when: "The DB entity service is hit"
RestResponse restResponse = rest.post("http://localhost:8080/api/someentity/$id");

then: "A 200 error is sent"
restResponse.status == 200


}


The problem I am having is the setup method blows up on .save() because there is not hibernate session. How can I manipulate my database before running a test?










share|improve this question













So we have a restful service that we want to test using a restclient in grails.



The test code should go something like this...



class MyControllerSpec extends Specification {

def setup() {
this.dbEntity = new DbEntity("someid123").save();
}

void "Test entity GET"{
given:
RestBuilder rest = new RestBuilder()

when: "The DB entity service is hit"
RestResponse restResponse = rest.post("http://localhost:8080/api/someentity/$id");

then: "A 200 error is sent"
restResponse.status == 200


}


The problem I am having is the setup method blows up on .save() because there is not hibernate session. How can I manipulate my database before running a test?







unit-testing grails integration-testing functional-testing spock






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Dec 3 '15 at 1:06









benstpierre

14.3k38144256




14.3k38144256












  • Are you tried to add in test "setup:" block?
    – Koloritnij
    Dec 3 '15 at 9:33


















  • Are you tried to add in test "setup:" block?
    – Koloritnij
    Dec 3 '15 at 9:33
















Are you tried to add in test "setup:" block?
– Koloritnij
Dec 3 '15 at 9:33




Are you tried to add in test "setup:" block?
– Koloritnij
Dec 3 '15 at 9:33












4 Answers
4






active

oldest

votes

















up vote
0
down vote













You can define a method named like "setupData", and call it in the "given" block of "Test entity GET" testcase.



def setupData() { this.dbEntity = new DbEntity("someid123").save(); }





share|improve this answer




























    up vote
    0
    down vote













    If you need to load some data before each funcional test, you can create a helper class, with @Shared variables or methods or both. Even you could override the setup, setupSpec methods in that class.



    Your first class does not extends Specification now, DataLoader class (helper class) instead.



    class MyControllerSpec extends DataLoader {

    void setup(){
    createEntity()
    }


    void "Test entity GET"{
    given:
    RestBuilder rest = new RestBuilder()

    when: "The DB entity service is hit"
    RestResponse restResponse = rest.post("http://localhost:8080/api/someentity/$dbEntity.id");

    then: "A 200 error is sent"
    restResponse.status == 200

    }
    }


    And your helper class is the one which extends Specification, with its methods and @Shared variables.



    import spock.lang.Shared

    class DataLoader extends Specification {

    @Shared DbEntity dbEntity

    void createEntity(){
    dbEntity = new DbEntity("someid123").save();
    }

    }





    share|improve this answer




























      up vote
      0
      down vote













      When extending GebSpec in Grails 2.5.6, none of the other answers helped: I would still get




      Method on class [...] was used outside of a Grails application




      on the save() call.



      Adding @TestFor(DbEntity) to the test class helped.



      NB: While that annotation breaks integration tests, it seems to be necessary here. Not sure why that is.






      share|improve this answer





















      • This only kind-of works if you have one type you need to do this with, and cleanup isn't really possible.
        – Raphael
        Nov 13 at 8:27


















      up vote
      0
      down vote













      You probably want to use the remote-control plugin. In Grails 2.x, add this to your BuildConfig.groovy:



      repositories {
      ...
      mavenRepo "http://dl.bintray.com/alkemist/maven/"
      }

      plugins {
      ...
      test ":remote-control:2.0"
      }


      After refreshing dependencies and potentially adjusting some settings (see e.g. here and here), you can use it like so in tests:



      // <project>/test/functional/<package>/MyControllerSpec.groovy
      class MyControllerSpec extends GebSpec {

      RemoteControl remote

      DbEntity dbEntity

      def setup() {
      this.remote = new RemoteControl()

      this.dbEntity = remote {
      new DbEntity("someid123").save()
      }
      }

      def cleanup() {
      remote {
      DbEntity.findAll().each { dbe ->
      println("Deleting $dbe")
      dbe.delete()
      }
      }
      }


      Note:




      • You can invoke remote in given/setup and when blocks as well.

      • Sometimes, it seems to be necessary to wrap core in remote { ... } in a DbEntity.withTransaction { ... }. Maybe that's obvious for the more intitiated; I stumbled over that.

      • If you want to return a DbEntity from remote it must be serializable.






      share|improve this answer





















        Your Answer






        StackExchange.ifUsing("editor", function () {
        StackExchange.using("externalEditor", function () {
        StackExchange.using("snippets", function () {
        StackExchange.snippets.init();
        });
        });
        }, "code-snippets");

        StackExchange.ready(function() {
        var channelOptions = {
        tags: "".split(" "),
        id: "1"
        };
        initTagRenderer("".split(" "), "".split(" "), channelOptions);

        StackExchange.using("externalEditor", function() {
        // Have to fire editor after snippets, if snippets enabled
        if (StackExchange.settings.snippets.snippetsEnabled) {
        StackExchange.using("snippets", function() {
        createEditor();
        });
        }
        else {
        createEditor();
        }
        });

        function createEditor() {
        StackExchange.prepareEditor({
        heartbeatType: 'answer',
        convertImagesToLinks: true,
        noModals: true,
        showLowRepImageUploadWarning: true,
        reputationToPostImages: 10,
        bindNavPrevention: true,
        postfix: "",
        imageUploader: {
        brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
        contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
        allowUrls: true
        },
        onDemand: true,
        discardSelector: ".discard-answer"
        ,immediatelyShowMarkdownHelp:true
        });


        }
        });














        draft saved

        draft discarded


















        StackExchange.ready(
        function () {
        StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f34056108%2fhow-can-i-setup-test-data-for-functional-testing-in-grails%23new-answer', 'question_page');
        }
        );

        Post as a guest















        Required, but never shown

























        4 Answers
        4






        active

        oldest

        votes








        4 Answers
        4






        active

        oldest

        votes









        active

        oldest

        votes






        active

        oldest

        votes








        up vote
        0
        down vote













        You can define a method named like "setupData", and call it in the "given" block of "Test entity GET" testcase.



        def setupData() { this.dbEntity = new DbEntity("someid123").save(); }





        share|improve this answer

























          up vote
          0
          down vote













          You can define a method named like "setupData", and call it in the "given" block of "Test entity GET" testcase.



          def setupData() { this.dbEntity = new DbEntity("someid123").save(); }





          share|improve this answer























            up vote
            0
            down vote










            up vote
            0
            down vote









            You can define a method named like "setupData", and call it in the "given" block of "Test entity GET" testcase.



            def setupData() { this.dbEntity = new DbEntity("someid123").save(); }





            share|improve this answer












            You can define a method named like "setupData", and call it in the "given" block of "Test entity GET" testcase.



            def setupData() { this.dbEntity = new DbEntity("someid123").save(); }






            share|improve this answer












            share|improve this answer



            share|improve this answer










            answered Dec 30 '15 at 10:58









            Andy.D

            14




            14
























                up vote
                0
                down vote













                If you need to load some data before each funcional test, you can create a helper class, with @Shared variables or methods or both. Even you could override the setup, setupSpec methods in that class.



                Your first class does not extends Specification now, DataLoader class (helper class) instead.



                class MyControllerSpec extends DataLoader {

                void setup(){
                createEntity()
                }


                void "Test entity GET"{
                given:
                RestBuilder rest = new RestBuilder()

                when: "The DB entity service is hit"
                RestResponse restResponse = rest.post("http://localhost:8080/api/someentity/$dbEntity.id");

                then: "A 200 error is sent"
                restResponse.status == 200

                }
                }


                And your helper class is the one which extends Specification, with its methods and @Shared variables.



                import spock.lang.Shared

                class DataLoader extends Specification {

                @Shared DbEntity dbEntity

                void createEntity(){
                dbEntity = new DbEntity("someid123").save();
                }

                }





                share|improve this answer

























                  up vote
                  0
                  down vote













                  If you need to load some data before each funcional test, you can create a helper class, with @Shared variables or methods or both. Even you could override the setup, setupSpec methods in that class.



                  Your first class does not extends Specification now, DataLoader class (helper class) instead.



                  class MyControllerSpec extends DataLoader {

                  void setup(){
                  createEntity()
                  }


                  void "Test entity GET"{
                  given:
                  RestBuilder rest = new RestBuilder()

                  when: "The DB entity service is hit"
                  RestResponse restResponse = rest.post("http://localhost:8080/api/someentity/$dbEntity.id");

                  then: "A 200 error is sent"
                  restResponse.status == 200

                  }
                  }


                  And your helper class is the one which extends Specification, with its methods and @Shared variables.



                  import spock.lang.Shared

                  class DataLoader extends Specification {

                  @Shared DbEntity dbEntity

                  void createEntity(){
                  dbEntity = new DbEntity("someid123").save();
                  }

                  }





                  share|improve this answer























                    up vote
                    0
                    down vote










                    up vote
                    0
                    down vote









                    If you need to load some data before each funcional test, you can create a helper class, with @Shared variables or methods or both. Even you could override the setup, setupSpec methods in that class.



                    Your first class does not extends Specification now, DataLoader class (helper class) instead.



                    class MyControllerSpec extends DataLoader {

                    void setup(){
                    createEntity()
                    }


                    void "Test entity GET"{
                    given:
                    RestBuilder rest = new RestBuilder()

                    when: "The DB entity service is hit"
                    RestResponse restResponse = rest.post("http://localhost:8080/api/someentity/$dbEntity.id");

                    then: "A 200 error is sent"
                    restResponse.status == 200

                    }
                    }


                    And your helper class is the one which extends Specification, with its methods and @Shared variables.



                    import spock.lang.Shared

                    class DataLoader extends Specification {

                    @Shared DbEntity dbEntity

                    void createEntity(){
                    dbEntity = new DbEntity("someid123").save();
                    }

                    }





                    share|improve this answer












                    If you need to load some data before each funcional test, you can create a helper class, with @Shared variables or methods or both. Even you could override the setup, setupSpec methods in that class.



                    Your first class does not extends Specification now, DataLoader class (helper class) instead.



                    class MyControllerSpec extends DataLoader {

                    void setup(){
                    createEntity()
                    }


                    void "Test entity GET"{
                    given:
                    RestBuilder rest = new RestBuilder()

                    when: "The DB entity service is hit"
                    RestResponse restResponse = rest.post("http://localhost:8080/api/someentity/$dbEntity.id");

                    then: "A 200 error is sent"
                    restResponse.status == 200

                    }
                    }


                    And your helper class is the one which extends Specification, with its methods and @Shared variables.



                    import spock.lang.Shared

                    class DataLoader extends Specification {

                    @Shared DbEntity dbEntity

                    void createEntity(){
                    dbEntity = new DbEntity("someid123").save();
                    }

                    }






                    share|improve this answer












                    share|improve this answer



                    share|improve this answer










                    answered Dec 30 '15 at 18:55









                    quindimildev

                    975518




                    975518






















                        up vote
                        0
                        down vote













                        When extending GebSpec in Grails 2.5.6, none of the other answers helped: I would still get




                        Method on class [...] was used outside of a Grails application




                        on the save() call.



                        Adding @TestFor(DbEntity) to the test class helped.



                        NB: While that annotation breaks integration tests, it seems to be necessary here. Not sure why that is.






                        share|improve this answer





















                        • This only kind-of works if you have one type you need to do this with, and cleanup isn't really possible.
                          – Raphael
                          Nov 13 at 8:27















                        up vote
                        0
                        down vote













                        When extending GebSpec in Grails 2.5.6, none of the other answers helped: I would still get




                        Method on class [...] was used outside of a Grails application




                        on the save() call.



                        Adding @TestFor(DbEntity) to the test class helped.



                        NB: While that annotation breaks integration tests, it seems to be necessary here. Not sure why that is.






                        share|improve this answer





















                        • This only kind-of works if you have one type you need to do this with, and cleanup isn't really possible.
                          – Raphael
                          Nov 13 at 8:27













                        up vote
                        0
                        down vote










                        up vote
                        0
                        down vote









                        When extending GebSpec in Grails 2.5.6, none of the other answers helped: I would still get




                        Method on class [...] was used outside of a Grails application




                        on the save() call.



                        Adding @TestFor(DbEntity) to the test class helped.



                        NB: While that annotation breaks integration tests, it seems to be necessary here. Not sure why that is.






                        share|improve this answer












                        When extending GebSpec in Grails 2.5.6, none of the other answers helped: I would still get




                        Method on class [...] was used outside of a Grails application




                        on the save() call.



                        Adding @TestFor(DbEntity) to the test class helped.



                        NB: While that annotation breaks integration tests, it seems to be necessary here. Not sure why that is.







                        share|improve this answer












                        share|improve this answer



                        share|improve this answer










                        answered Nov 8 at 11:31









                        Raphael

                        3,3212851




                        3,3212851












                        • This only kind-of works if you have one type you need to do this with, and cleanup isn't really possible.
                          – Raphael
                          Nov 13 at 8:27


















                        • This only kind-of works if you have one type you need to do this with, and cleanup isn't really possible.
                          – Raphael
                          Nov 13 at 8:27
















                        This only kind-of works if you have one type you need to do this with, and cleanup isn't really possible.
                        – Raphael
                        Nov 13 at 8:27




                        This only kind-of works if you have one type you need to do this with, and cleanup isn't really possible.
                        – Raphael
                        Nov 13 at 8:27










                        up vote
                        0
                        down vote













                        You probably want to use the remote-control plugin. In Grails 2.x, add this to your BuildConfig.groovy:



                        repositories {
                        ...
                        mavenRepo "http://dl.bintray.com/alkemist/maven/"
                        }

                        plugins {
                        ...
                        test ":remote-control:2.0"
                        }


                        After refreshing dependencies and potentially adjusting some settings (see e.g. here and here), you can use it like so in tests:



                        // <project>/test/functional/<package>/MyControllerSpec.groovy
                        class MyControllerSpec extends GebSpec {

                        RemoteControl remote

                        DbEntity dbEntity

                        def setup() {
                        this.remote = new RemoteControl()

                        this.dbEntity = remote {
                        new DbEntity("someid123").save()
                        }
                        }

                        def cleanup() {
                        remote {
                        DbEntity.findAll().each { dbe ->
                        println("Deleting $dbe")
                        dbe.delete()
                        }
                        }
                        }


                        Note:




                        • You can invoke remote in given/setup and when blocks as well.

                        • Sometimes, it seems to be necessary to wrap core in remote { ... } in a DbEntity.withTransaction { ... }. Maybe that's obvious for the more intitiated; I stumbled over that.

                        • If you want to return a DbEntity from remote it must be serializable.






                        share|improve this answer

























                          up vote
                          0
                          down vote













                          You probably want to use the remote-control plugin. In Grails 2.x, add this to your BuildConfig.groovy:



                          repositories {
                          ...
                          mavenRepo "http://dl.bintray.com/alkemist/maven/"
                          }

                          plugins {
                          ...
                          test ":remote-control:2.0"
                          }


                          After refreshing dependencies and potentially adjusting some settings (see e.g. here and here), you can use it like so in tests:



                          // <project>/test/functional/<package>/MyControllerSpec.groovy
                          class MyControllerSpec extends GebSpec {

                          RemoteControl remote

                          DbEntity dbEntity

                          def setup() {
                          this.remote = new RemoteControl()

                          this.dbEntity = remote {
                          new DbEntity("someid123").save()
                          }
                          }

                          def cleanup() {
                          remote {
                          DbEntity.findAll().each { dbe ->
                          println("Deleting $dbe")
                          dbe.delete()
                          }
                          }
                          }


                          Note:




                          • You can invoke remote in given/setup and when blocks as well.

                          • Sometimes, it seems to be necessary to wrap core in remote { ... } in a DbEntity.withTransaction { ... }. Maybe that's obvious for the more intitiated; I stumbled over that.

                          • If you want to return a DbEntity from remote it must be serializable.






                          share|improve this answer























                            up vote
                            0
                            down vote










                            up vote
                            0
                            down vote









                            You probably want to use the remote-control plugin. In Grails 2.x, add this to your BuildConfig.groovy:



                            repositories {
                            ...
                            mavenRepo "http://dl.bintray.com/alkemist/maven/"
                            }

                            plugins {
                            ...
                            test ":remote-control:2.0"
                            }


                            After refreshing dependencies and potentially adjusting some settings (see e.g. here and here), you can use it like so in tests:



                            // <project>/test/functional/<package>/MyControllerSpec.groovy
                            class MyControllerSpec extends GebSpec {

                            RemoteControl remote

                            DbEntity dbEntity

                            def setup() {
                            this.remote = new RemoteControl()

                            this.dbEntity = remote {
                            new DbEntity("someid123").save()
                            }
                            }

                            def cleanup() {
                            remote {
                            DbEntity.findAll().each { dbe ->
                            println("Deleting $dbe")
                            dbe.delete()
                            }
                            }
                            }


                            Note:




                            • You can invoke remote in given/setup and when blocks as well.

                            • Sometimes, it seems to be necessary to wrap core in remote { ... } in a DbEntity.withTransaction { ... }. Maybe that's obvious for the more intitiated; I stumbled over that.

                            • If you want to return a DbEntity from remote it must be serializable.






                            share|improve this answer












                            You probably want to use the remote-control plugin. In Grails 2.x, add this to your BuildConfig.groovy:



                            repositories {
                            ...
                            mavenRepo "http://dl.bintray.com/alkemist/maven/"
                            }

                            plugins {
                            ...
                            test ":remote-control:2.0"
                            }


                            After refreshing dependencies and potentially adjusting some settings (see e.g. here and here), you can use it like so in tests:



                            // <project>/test/functional/<package>/MyControllerSpec.groovy
                            class MyControllerSpec extends GebSpec {

                            RemoteControl remote

                            DbEntity dbEntity

                            def setup() {
                            this.remote = new RemoteControl()

                            this.dbEntity = remote {
                            new DbEntity("someid123").save()
                            }
                            }

                            def cleanup() {
                            remote {
                            DbEntity.findAll().each { dbe ->
                            println("Deleting $dbe")
                            dbe.delete()
                            }
                            }
                            }


                            Note:




                            • You can invoke remote in given/setup and when blocks as well.

                            • Sometimes, it seems to be necessary to wrap core in remote { ... } in a DbEntity.withTransaction { ... }. Maybe that's obvious for the more intitiated; I stumbled over that.

                            • If you want to return a DbEntity from remote it must be serializable.







                            share|improve this answer












                            share|improve this answer



                            share|improve this answer










                            answered Nov 13 at 10:00









                            Raphael

                            3,3212851




                            3,3212851






























                                draft saved

                                draft discarded




















































                                Thanks for contributing an answer to Stack Overflow!


                                • Please be sure to answer the question. Provide details and share your research!

                                But avoid



                                • Asking for help, clarification, or responding to other answers.

                                • Making statements based on opinion; back them up with references or personal experience.


                                To learn more, see our tips on writing great answers.





                                Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


                                Please pay close attention to the following guidance:


                                • Please be sure to answer the question. Provide details and share your research!

                                But avoid



                                • Asking for help, clarification, or responding to other answers.

                                • Making statements based on opinion; back them up with references or personal experience.


                                To learn more, see our tips on writing great answers.




                                draft saved


                                draft discarded














                                StackExchange.ready(
                                function () {
                                StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f34056108%2fhow-can-i-setup-test-data-for-functional-testing-in-grails%23new-answer', 'question_page');
                                }
                                );

                                Post as a guest















                                Required, but never shown





















































                                Required, but never shown














                                Required, but never shown












                                Required, but never shown







                                Required, but never shown

































                                Required, but never shown














                                Required, but never shown












                                Required, but never shown







                                Required, but never shown







                                這個網誌中的熱門文章

                                Academy of Television Arts & Sciences

                                L'Équipe

                                1995 France bombings