views:

869

answers:

2

Hi,

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

A: 

According to this document, mocking static methods doesn't currently work.

laz
unfortunately, I think this is not the issue here. The exception happens already on this line:def c = mockFor(GlobalHelper)Static method isn't even mentioned yet in in this part of code...
mr.cezar
A: 

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
    }
}
Colin Harrington
I'm using Grails 1.1, so this might be the issue. GrailsUnitTestCase is extended, but something is broken. Grails 1.1.1 is currently not an option, so I did this and it's working:GlobalHelper.metaClass.static.getRandomString = { -> return "nestoABC" }
mr.cezar
Gotta be careful when adding methods to the metaClass. You'll want to make sure you clean them up or you might run into issues with other tests.Does my test work if you run it within your test suite?
Colin Harrington