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