Spock: Using ConfineMetaClassChanges when using MetaClass mocking

One of the handy features of Groovy is to change the behavior of classes using MOP (Meta-Object Protocol). We change the metaClass property of a class to alter an implementation. You can for example override a static method of a class. See the example below:

However this way of mocking has a nasty side effect. Since we apply changes on the User on class level, the changes are also applied in all our other test cases. This can have some unexpected behavior in your other tests

To prevent this Spock has introduced the @ConfineMetaClassChanges annotation. This annotation makes sure the class will return to its original state when it was used in our test.

See the example below:

Be aware: this means when some other test did changes to the User class without using @ConfineMetaClassChanges, these changes will be still applicable when the test which has @ConfineMetaClassChanges restores the User class to its old state.

Leave a Reply

Your email address will not be published. Required fields are marked *