簡體   English   中英

Grails:使用域類的單元測試控制器方法

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

    }    
}

試試這個。

在控制器測試用例的頂部使用@TestFor(AuthorController)注釋。 在擴展Specification類之后,括號也不能存在。 只是想確認一下,這個問題可能是錯字。 如果問題仍然存在,請嘗試安裝Grails webxml插件。

這里查看更多信息。

希望有所幫助!

謝謝,
SA

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM