mardi 5 juillet 2016

preventing metaclass changes from causing test pollution

My Grails 2.5.X app has this class

@Singleton
class TokenFactory {

    String nextToken() {
        UUID.randomUUID().toString()
    }
}

In a Spock unit test I stub it like so

class MySpec extends Specification {

    def 'test something'() {

        TokenFactory.metaClass.nextToken = { ->
            'dummy-token'
        }

        expect:
        TokenFactory.instance.nextToken() == 'dummy-token' // not the actual test :)
    }
}

This works fine, but when I run the entire test suite, the stubbing is also applied when the integration tests are run, causing them to fail. I need to confine the changes to the meta-class to just MySpec. I've tried the following, but none of them work

  • annotating MySpec with @ConfineMetaClassChanges
  • setting TokenFactory.metaClass = null in a cleanup block/method
  • capturing the original meta-class and setting TokenFactory.metaClass = originalMetaClass in a cleanup block/method

Aucun commentaire:

Enregistrer un commentaire