gpt4 book ai didi

java - 使用 void 返回类型链接来自 spock stub 的副作用

转载 作者:行者123 更新时间:2023-11-29 03:07:05 24 4
gpt4 key购买 nike

我正在尝试测试以下(设计的)代码,该代码会进行调用,并在调用失败时尝试重试。

 public class MyObject
{
public void process(final Client client) throws IOException
{
try
{
client.send();
}
catch (IOException e)
{
client.fix();
}

try
{
client.send();
}
catch (IOException e)
{
throw new IOException(e);
}
}

public class Client
{
public void send() throws IOException {}

public void fix() {}
}
}

我的测试策略是模拟 client 对象并 stub 响应,该响应将在第一次调用 send() 时抛出异常,然后在第二次尝试时成功.

使用 spock,我有以下内容:

def "test method calls"() {
setup:
def MyObject myObject = new MyObject()
def Client client = Mock(Client)

when:
myObject.process(client)

then:
2 * client.send() >>> {throw new IOException()} >> void
}

我已经尝试了上面的方法,并将 void 替换为 null,并不断收到转换异常。

我也试过:

2 * client.send() >>> [{throw new MyException()}, void]

如何模拟我想要的响应?

最佳答案

这个测试通过了。我添加了注释以显示每个步骤指示的内容:

def "test method calls"() {
given:
def MyObject myObject = new MyObject()
def MyObject.Client client = Mock(MyObject.Client)
//The first time client.send() is called, throw an exception
1 * client.send() >> {throw new IOException()}
//The second time client.send() is called, do nothing. With the above, also defines that client.send() should be called a total of 2 times.
1 * client.send()
when:
myObject.process(client)
then:
noExceptionThrown() //Verifies that no exceptions are thrown
1 * client.fix() // Verifies that client.fix() is called only once.
}

关于java - 使用 void 返回类型链接来自 spock stub 的副作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31608808/

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