Grails: Unit Test 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, the author is the domain class that maps to the table in the 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: A method of the [com.mypackage.Author] class was used outside of the Grails application. If you run in the context of a test using mocking API or bootstrapping Grails correctly.
Can someone tell me how to check my actions correctly? I am having trouble mocking the Author.findByFirstName () method.
I am using Grails 2.4.2
Thank.
source to share
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 it.
source to share
Use the annotation @TestFor(AuthorController)
at the top in your controller test case. Also, parentheses must not be present after class extension Specification
. Just wanted to confirm it might be a typo in the question. If the problem still persists, try installing the Grails webxml plugin .
Take a look here for more information.
Hope it helps!
Thanks,
SA
source to share