Search code examples
unit-testinggrailsgrails-domain-classgrails-controller

Grails: Unit testing controller method with domain class


I have a simple grails controller:

class AuthorController {

    def index(){
       def authors = Author.findByFirstName("Albert")
       render (view: "author-page", model: ["authors":authors])

   }
}

Here, Author is a domain class that maps to a table in SQL database.

I am trying to write a unit test for it like this:

import grails.test.mixin.Mock

@Mock(Author)
class AuthorControllerSpec extends Specification {

    void "when index is called, authorPage view is rendered"() {
          when:
               controller.index()
          then:
               view == "/author-page"

    }    

}

But when I run this test, I keep getting java.lang.IllegalStateException: Method on class [com.mypackage.Author] was used outside of a Grails application. If running in the context of a test using the mocking API or bootstrap Grails correctly.

Can someone tell me how to properly test my action? I am having trouble mocking that Author.findByFirstName() method.

I am using Grails 2.4.2

Thanks.


Solution

  • import grails.test.mixin.Mock
    import grails.test.mixin.TestFor
    import spock.lang.Specification
    
    @TestFor(AuthorController)
    @Mock([Author])
    class AuthorControllerSpec extends Specification {
    
        void "when index is called, authorPage view is rendered"() {
              when:
                   controller.index()
              then:
                   view == "/author-page"
    
        }    
    }
    

    Try this.