Reputation: 630
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?
Upvotes: 0
Views: 1829
Reputation: 630
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.
Upvotes: 0
Reputation: 27245
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?
Yes, it is possible. The specifics of how best to do it will depend on specifically what you want to accomplish but global extensions are likely candidates. See the "Writing Custom Extensions" section of http://spockframework.org/spock/docs/1.3/extensions.html for a lot of detail. There is a lot of flexibility there. We had great success writing custom extensions for Micronaut.
I hope that helps.
Upvotes: 3