繁体   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