覆盖 spock 中的测试

Override test in spock

我有一个用 base class

编写的测试
abstract class BaseEdgeSpec extends Specification {
    Edge edge
    Edge switched
    abstract def 'equals with both vertices switched'()
}

还有两个class我想实现这个测试。一个用于正常边缘

class EdgeTestSpec extends BaseEdgeSpec {
    def setup() {
        edge = new Edge(one:'step1', two:'step2')
        switched = new Edge(one: 'step2', two: 'step1')
    }
    @Override
    def 'equals with both vertices switched'() {
        expect:
        edge == switched
    }
}

还有一个用于有向边

public class DirectedEdgeSpec extends BaseEdgeSpec {
    def setup() {
        edge = new DirectedEdge(one:'step1', two:'step2')
        switched = new DirectedEdge(one:'step2', two:'step1')
    }
    @Override
    def 'equals with both vertices switched'() {
        expect:
        edge != switched
    }
}

当我 运行 测试时出现这些错误

/etc/user/john/projects/graph-dsl/src/test/groovy/nondsl/edges/DirectedEdgeSpec.groovy: 6: Can't have an abstract method in a non-abstract class. The class 'nondsl.edges.DirectedEdgeSpec' must be declared abstract or the method 'java.lang.Object equals with both vertices switched()' must be implemented.
 @ line 6, column 1.
   public class DirectedEdgeSpec extends BaseEdgeSpec {
   ^
/etc/user/john/projects/graph-dsl/src/test/groovy/nondsl/edges/DirectedEdgeSpec.groovy: 16: Method '$spock_feature_1_0' from class 'nondsl.edges.DirectedEdgeSpec' does not override method from its superclass or interfaces but is annotated with @Override.
 @ line 16, column 5.
       @Override
       ^
/etc/user/john/projects/graph-dsl/src/test/groovy/nondsl/edges/EdgeTestSpec.groovy: 16: Method '$spock_feature_1_0' from class 'nondsl.edges.EdgeTestSpec' does not override method from its superclass or interfaces but is annotated with @Override.
 @ line 16, column 5.
       @Override
       ^
3 errors

如何正确覆盖这些测试?

你可能做不到。 Spock 转换所有 "feature methods"(您的测试),以便它们最终在字节代码中被称为 $spock_feature_%d_%d。因此错误消息 "Method '$spock_feature_1_0' [...] does not override method from its superclass or interfaces but is annotated with @Override."

org.spockframework.compiler.SpecParser.isFeatureMethod(MethodNode) org.spockframework.compiler.SpecRewriter.createInternalName(FeatureMethod)

作为覆盖的替代方法,您仍然可以将测试逻辑提取到超类方法中,并从子类的测试中调用它。