使用 spock 进行单元测试 "Too few invocations"
Getting "Too few invocations" on unit test with spock
为简单起见,我们取一个非常简单的 class:
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()
}
}
通过执行此测试,我收到以下错误:
Running method 1 Running method 2
Too few invocations for:
1 * tesingClass.method2() (0 invocations)
为什么会出现此错误?打印的日志显示 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");
}
}
为简单起见,我们取一个非常简单的 class:
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()
}
}
通过执行此测试,我收到以下错误:
Running method 1 Running method 2
Too few invocations for:
1 * tesingClass.method2() (0 invocations)
为什么会出现此错误?打印的日志显示 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");
}
}