Grails:使用域类的单元测试控制器方法

时间:2014-12-23 23:17:06

标签: unit-testing grails grails-domain-class grails-controller

我有一个简单的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

感谢。

2 个答案:

答案 0 :(得分: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"

    }    
}

试试这个。

答案 1 :(得分:0)

在控制器测试用例的顶部使用@TestFor(AuthorController)注释。在扩展Specification类之后,括号也不能存在。只是想确认一下,这个问题可能是错字。如果问题仍然存在,请尝试安装Grails webxml插件。

请查看here以获取更多信息。

希望有所帮助!

谢谢,
SA

相关问题