bat*_*man 4 java unit-testing spock
spock是否有像TestNg一样的Test事件监听器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(ErrorListenerExtension)
@interface ListenForErrors {}
Run Code Online (Sandbox Code Playgroud)
扩展(更新):
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"
}
}
Run Code Online (Sandbox Code Playgroud)
听众:
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
}
}
Run Code Online (Sandbox Code Playgroud)
然后,您可以在Spec类或方法上使用新注释:
@ListenForErrors
class MySpec extends Specification {
...
}
Run Code Online (Sandbox Code Playgroud)
全球
这也有三个部分:扩展,监听器和注册.
class ListenForErrorsExtension implements IGlobalExtension {
void visitSpec(SpecInfo specInfo) {
specInfo.addListener(new ListenForErrorsListener())
}
}
Run Code Online (Sandbox Code Playgroud)
您可以使用与ListenForErrorsListener上面相同的类.
要注册扩展,请创建目录中指定org.spockframework.runtime.extension.IGlobalExtension的META-INF/services文件.如果使用Gradle/Maven,这将是src/test/resources.此文件应仅包含全局扩展的完全限定类名,例如:
com.example.tests.ListenForErrorsExtension
Run Code Online (Sandbox Code Playgroud)
参考
例如,请参阅Spock内置扩展:https : //github.com/spockframework/spock/tree/groovy-1.8/spock-core/src/main/java/spock/lang https://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")
}
Run Code Online (Sandbox Code Playgroud)
请参阅文档中基于交互的测试