gpt4 book ai didi

spock - 使用 spock 在单元测试中获取 "Too few invocations"

转载 作者:行者123 更新时间:2023-12-04 12:20:13 24 4
gpt4 key购买 nike

为简单起见,我们来看一个非常简单的类:

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");
}
}

关于spock - 使用 spock 在单元测试中获取 "Too few invocations",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28867202/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com