繁体   English   中英

Grails域单元测试-MockFor()

[英]Grails domain unit testing - mockFor()

这是域类:

class Registration {

  String email
  String generatedKey

  def beforeInsert = {
      String newToken = GlobalHelper.getRandomString()
      generatedKey = newToken
  }
}

这是单元测试的相关部分:

    def c = mockFor(GlobalHelper)
    c.demand.static.getRandomString {-> return "nestoABC" }
    c.createMock()
    reg.beforeInsert()

运行测试时,出现此错误:


没有这样的属性:类的GlobalHelper:RegistrationTests

groovy.lang.MissingPropertyException:否这样的属性:类的GlobalHelper:RegistrationTests.testConstraints(RegistrationTests.groovy:57)上的RegistrationTests


GlobalHelper类位于Groovy源文件夹中,提到的第57行是带有嘲笑()方法的行。

Grails Testing文档对于此问题不是很有帮助...

我知道可以使用集成测试轻松解决此问题,但我认为它也应该以这种方式工作。

提前致谢

根据文档,模拟静态方法当前不起作用。

您正在使用哪个版本的Grails?

使用Grails 1.1.1,以下测试适用于上述Registration域。 这应该在带有测试插件的Grails 1.1+和Grails 1.0.x上运行。

您需要确保您的单元测试扩展了GrailsUnitTestCase 我犯了很多次错误。

import grails.test.*

class RegistrationTests extends GrailsUnitTestCase {

    void testBeforeInsert() {
        def reg = new Registration()
        reg.generatedKey = "preBeforeInsert"
        String randomString = "nestoABC"

        def c = mockFor(GlobalHelper)
        c.demand.static.getRandomString {-> return randomString }

        assertNotSame(reg.generatedKey, randomString)
        reg.beforeInsert()
        assertSame(reg.generatedKey, randomString)

        c.verify() //Verify the demands
    }
}

我遇到了这个问题,并通过完全限定要模拟的类的类名来解决了这个问题。 因此,对于您的示例:

def c = mockFor(GlobalHelper)

会成为

def c = mockFor(com.example.fully.qualified.GlobalHelper)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM