![](/img/trans.png)
[英]Grails 3 Controller Unit Testing: Domain class validation not working in a ControllerUnitTest
[英]Grails: Unit testing controller method with domain class
我有一个简单的grails控制器:
class AuthorController {
def index(){
def authors = Author.findByFirstName("Albert")
render (view: "author-page", model: ["authors":authors])
}
}
这里,Author是一个映射到SQL数据库中的表的域类。
我正在尝试为它编写单元测试:
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"
}
}
但是,当我运行此测试时,我不断收到java.lang.IllegalStateException:类[com.mypackage.Author]上的方法在Grails应用程序之外使用。 如果在测试的上下文中使用模拟API或正确引导Grails运行。
有人能告诉我如何正确测试我的行为吗? 我在模拟Author.findByFirstName()方法时遇到问题。
我正在使用Grails 2.4.2
谢谢。
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"
}
}
试试这个。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.