Grails:使用域类对控制器方法进行单元测试

3

我有一个简单的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错误:在Grails应用程序之外使用了类[com.mypackage.Author]上的方法。如果在使用模拟API或正确引导Grails的测试上下文中运行,请解决此问题。

有人能告诉我如何正确地测试我的操作吗?我无法模拟Author.findByFirstName()方法。

我正在使用Grails 2.4.2

谢谢。

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

谢谢。我在顶部使用@TestFor,但仍然不起作用。括号不在那里。感谢您发现了这个问题。我已经将其删除。 - Stealth

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接