【发布时间】:2015-07-24 10:57:36
【问题描述】:
我正在尝试测试以下(人为的)代码,它会进行调用,并在调用失败时尝试重试。
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 对象并存根响应,该响应将在第一次调用 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]
如何模拟我想要的响应?
【问题讨论】:
-
client.send() >> { throw new MyException() } >> null -
我试过了,没用
-
对我来说很好用,我设计它就是为了这样工作。也许您尝试了一些稍微不同的东西,例如使用
>>>而不是>>在您的问题中,这是行不通的。 -
我确认,Peter 的解决方案运行良好。