斯波克有测试事件监听器吗



spock是否有任何测试事件监听器,就像TestNg有ITestListener一样?

这样,当测试用例失败时,我就可以访问。

Spock确实有侦听器。不幸的是,在其他方面都很优秀的官方文件有";TODO";在编写自定义扩展下:http://spockframework.github.io/spock/docs/1.0/extensions.html.

更新:官方文档已更新,包含有关自定义扩展的有用信息:http://spockframework.org/spock/docs/1.1/extensions.html.有关更多详细信息,请参阅这些。

有两种方法:基于注释的全局

基于注释的

这里有三个部分:注释、扩展和侦听器。

注释:

    import java.lang.annotation.*
    import org.spockframework.runtime.extension.ExtensionAnnotation
    @Retention(RetentionPolicy.RUNTIME)
    @Target([ElementType.TYPE, ElementType.METHOD])
    @ExtensionAnnotation(ListenForErrorsExtension)
    @interface ListenForErrors {}

扩展(更新):

    import org.spockframework.runtime.extension.AbstractAnnotationDrivenExtension
    import org.spockframework.runtime.model.SpecInfo
    class ListenForErrorsExtension extends AbstractAnnotationDrivenExtension<ListenForErrors> {
        void visitSpec(SpecInfo spec) {
            spec.addListener(new ListenForErrorsListener())
        }
       @Override
       void visitSpecAnnotation(ListenForErrors annotation, SpecInfo spec){
        println "do whatever you need here if you do. This method will throw an error unless you override it"
    }
    }

听众:

    import org.spockframework.runtime.AbstractRunListener
    import org.spockframework.runtime.model.ErrorInfo
    class ListenForErrorsListener extends AbstractRunListener {
        void error(ErrorInfo error) {
            println "Test failed: ${error.method.name}"
            // Do other handling here
        }
    }

然后,您可以在Spec类或方法上使用新的注释:

    @ListenForErrors
    class MySpec extends Specification {
        ...
    }

全局

它还有三个部分:扩展、侦听器和注册。

    class ListenForErrorsExtension implements IGlobalExtension {
        void visitSpec(SpecInfo specInfo) {
            specInfo.addListener(new ListenForErrorsListener())
        }
    }

您可以使用与上面相同的ListenForErrorsListener类。

要注册扩展名,请在META-INF/services目录中创建一个名为org.spockframework.runtime.extension.IGlobalExtension的文件。如果使用Gradle/Maven,这将在src/test/resources下。这个文件应该只包含全局扩展名的完全限定类名,例如:

com.example.tests.ListenForErrorsExtension

参考

例如,请参阅此处的Spock内置扩展:https://github.com/spockframework/spock/tree/groovy-1.8/spock-core/src/main/java/spock/langhttps://github.com/spockframework/spock/tree/groovy-1.8/spock-core/src/main/java/org/spockframework/runtime/extension/builtin

Spock通过Mock:进行交互监听

def "should send messages to all subscribers"() {
    given:
    def subscriber = Mock(Subscriber)
    when:
    publisher.send("hello")
    then:
    1 * subscriber.receive("hello")
}

请参阅文档

中基于交互的测试

最新更新