使用 spock 进行单元测试"Too few invocations"



为了简单起见,让我们使用一个非常简单的类:

public class TestingClass {
    public void method1(){
        System.out.println("Running method 1");
        method2();
    }
    public void method2(){
        System.out.println("Running method 2");
    }
}

现在我正在编写一个简单的测试,检查当我们调用method1()时,是否调用了method2()

class TestingClassSpec extends Specification {
    void "method2() is invoked by method1()"() {
        given:
        def tesingClass = new TestingClass()
        when:
        tesingClass.method1()
        then:
        1 * tesingClass.method2()
    }
}

通过执行这个测试,我得到了以下错误:

运行方法1运行方法2

调用次数太少:

1*tesingClass.method2()(0次调用)

为什么我会出现这个错误?打印的日志显示调用了method2()

在实际对象上测试交互时,需要使用Spy,请参阅以下内容:

@Grab('org.spockframework:spock-core:0.7-groovy-2.0')
@Grab('cglib:cglib-nodep:3.1')
import spock.lang.*
class TestingClassSpec extends Specification {
    void "method2() is invoked by method1()"() {
        given:
        TestingClass tesingClass = Spy()
        when:
        tesingClass.method1()
        then:
        1 * tesingClass.method2()
    }
}
public class TestingClass {
    public void method1(){
        System.out.println("Running method 1");
        method2();
    }
    public void method2(){
        System.out.println("Running method 2");
    }
}

相关内容

最新更新