简体   繁体   中英

Is it possible to have a global setup method in Spock test?

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?

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM