【问题标题】:Grails: Unit testing controller method with domain classGrails:具有域类的单元测试控制器方法
【发布时间】:2015-02-22 03:06:24
【问题描述】:

我有一个简单的 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: Method on class [com.mypackage.Author] was used outside Grails 应用程序。如果在使用模拟 API 或引导 Grails 的测试上下文中正确运行。

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

我正在使用 Grails 2.4.2

谢谢。

【问题讨论】:

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


    【解决方案1】:
    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"
    
        }    
    }
    

    试试这个。

    【讨论】:

      【解决方案2】:

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

      查看here 了解更多信息。

      希望有帮助!

      谢谢,

      【讨论】:

      • 谢谢。我在顶部使用@TestFor,仍然无法正常工作。括号不存在。谢谢你抓住那个。我已将其删除。
      猜你喜欢
      • 2014-06-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-09-14
      相关资源
      最近更新 更多