3

我有一個簡單的Grails控制器:的Grails:單元測試控制器法域類

class AuthorController { 

    def index(){ 
     def authors = Author.findByFirstName("Albert") 
     render (view: "author-page", model: ["authors":authors]) 

    } 
} 

在這裏,作者是映射到表中的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

謝謝。

回答

4
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" 

    }  
} 

試試這個。

0

在控制器測試用例的頂部使用@TestFor(AuthorController)註釋。此外,在延伸Specification課程後,方括號不得存在。只是想確認,這可能是錯誤的問題。如果問題仍然存在,請嘗試安裝Grails webxml插件。

查看here瞭解更多信息。

希望有幫助!

感謝,
SA

+0

謝謝。我在頂部使用@TestFor,仍然不起作用。括號不在那裏。感謝您的支持。我已經刪除它。 – Stealth