[英]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.