简体   繁体   English

是否可以在 Spock 测试中使用全局设置方法?

[英]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.我是 Grails/Groovy 应用程序的开发人员,该应用程序使用 Spock 作为其单元测试框架。 The project has around 1000 unit tests, and I would essentially like to perform a specific mock / operation before running all tests.该项目有大约 1000 个单元测试,我基本上想在运行所有测试之前执行特定的模拟/操作。 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.有关详细信息,请参阅http://spockframework.org/spock/docs/1.3/extensions.html的“编写自定义扩展”部分。 There is a lot of flexibility there.那里有很大的灵活性。 We had great success writing custom extensions for Micronaut.我们在为 Micronaut 编写自定义扩展方面取得了巨大成功。

I hope that helps.我希望这有帮助。

We ended up doing the following.我们最终做了以下事情。 First we defined a class implementing IAnnotationDrivenExtension interface:首先我们定义了一个实现 IAnnotationDrivenExtension 接口的类:

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.现在,每当我们使用 MockConfigMap 注释对 Spec 类进行注释时,都会调用 visitSpecAnnotation 方法,并获得所需的行为。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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