I am a developer on a Grails/Groovy application which uses Spock as its framework for unit testing. The project has around 1000 unit tests, and I would essentially like to perform a specific mock / operation before running all tests. Preferably it should only be executed once, alternatively before each test - or before some large subset of all the tests. I imagine that it out to be possible to have a “global” setup method which all tests can extend. Is this possible?
We ended up doing the following. First we defined a class implementing IAnnotationDrivenExtension interface:
class MockConfigMapExtension implements IAnnotationDrivenExtension<MockConfigMap> {
@Override
void visitSpecAnnotation(MockConfigMap annotation, SpecInfo spec) {
// WRITE THE RELEVANT STARTUP CODE HERE
}
@Override
void visitFeatureAnnotation(MockConfigMap annotation, FeatureInfo feature) {
}
@Override
void visitFixtureAnnotation(MockConfigMap annotation, MethodInfo fixtureMethod) {
}
@Override
void visitFieldAnnotation(MockConfigMap annotation, FieldInfo field) {
}
@Override
void visitSpec(SpecInfo spec) {
}
}
where we defined this trivial annotation:
@Retention(RetentionPolicy.RUNTIME)
@Target([ElementType.TYPE])
@ExtensionAnnotation(MockConfigMapExtension.class)
@interface MockConfigMap {
}
Now, whenever we annotate a Spec class with the MockConfigMap annotation, the visitSpecAnnotation method is invoked, and we get the desired behaviour.