简体   繁体   中英

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

groovy.lang.MissingPropertyException: No such property: GlobalHelper for class: RegistrationTests at RegistrationTests.testConstraints(RegistrationTests.groovy:57)


The GlobalHelper class is located in Groovy source folder, and the mentioned line 57 is the line with the mockFor() method.

Grails Testing docs were not very helpfull regarding this issue...

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?

Using Grails 1.1.1 the following test works with your Registration domain as listed above. This should run on Grails 1.1+ and Grails 1.0.x with the testing plugin.

You'll want to make sure that your unit test extends 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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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