在spock

时间:2017-11-26 03:33:54

标签: groovy spock

我在基类中编写了一个测试

abstract class BaseEdgeSpec extends Specification {
    Edge edge
    Edge switched
    abstract def 'equals with both vertices switched'()
}

我想要实现这个测试的两个类。一个用于正常边缘

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

如何正确覆盖这些测试?

1 个答案:

答案 0 :(得分:1)

你可能不能。 Spock转换所有"特征方法" (您的测试),以便最终在字节代码中调用$spock_feature_%d_%d。因此错误消息" Method' $ spock_feature_1_0' [...]不会覆盖超类或接口的方法,但会使用@Override进行注释。"

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

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