Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 772
Stealth Avatar asked Apr 22 '26 15:04

Stealth


1 Answers

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.

like image 144
Anand Kushwaha Avatar answered Apr 24 '26 05:04

Anand Kushwaha



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!