简体   繁体   English

Grails域单元测试-MockFor()

[英]Grails domain unit testing - mockFor()

This is the domain class: 这是域类:

class Registration {

  String email
  String generatedKey

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

and this is the relevant part of the unit test: 这是单元测试的相关部分:

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

When running the test, I get this error: 运行测试时,出现此错误:


No such property: GlobalHelper for class: RegistrationTests 没有这样的属性:类的GlobalHelper:RegistrationTests

groovy.lang.MissingPropertyException: No such property: GlobalHelper for class: RegistrationTests at RegistrationTests.testConstraints(RegistrationTests.groovy:57) groovy.lang.MissingPropertyException:否这样的属性:类的GlobalHelper:RegistrationTests.testConstraints(RegistrationTests.groovy:57)上的RegistrationTests


The GlobalHelper class is located in Groovy source folder, and the mentioned line 57 is the line with the mockFor() method. GlobalHelper类位于Groovy源文件夹中,提到的第57行是带有嘲笑()方法的行。

Grails Testing docs were not very helpfull regarding this issue... Grails Testing文档对于此问题不是很有帮助...

I know this would be easily solved using integration tests, but I think it should also work this way. 我知道可以使用集成测试轻松解决此问题,但我认为它也应该以这种方式工作。

Thanks in advance 提前致谢

According to this document, mocking static methods doesn't currently work. 根据文档,模拟静态方法当前不起作用。

Which version of Grails are you using? 您正在使用哪个版本的Grails?

Using Grails 1.1.1 the following test works with your Registration domain as listed above. 使用Grails 1.1.1,以下测试适用于上述Registration域。 This should run on Grails 1.1+ and Grails 1.0.x with the testing plugin. 这应该在带有测试插件的Grails 1.1+和Grails 1.0.x上运行。

You'll want to make sure that your unit test extends GrailsUnitTestCase . 您需要确保您的单元测试扩展了GrailsUnitTestCase I've made that mistake a number of times. 我犯了很多次错误。

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
    }
}

I had this problem and resolved it by fully qualifying the Class name of the class to be mocked. 我遇到了这个问题,并通过完全限定要模拟的类的类名来解决了这个问题。 So for your example: 因此,对于您的示例:

def c = mockFor(GlobalHelper)

would become 会成为

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

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

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