我正在尝试测试以下(人为的)代码,该代码会进行调用,如果调用失败,则会尝试重试。
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
}
我已经尝试了上述操作,并将null替换为null,并继续获得强制转换异常。
我也试过了:
2 * client.send() >>> [{throw new MyException()}, void]
我如何模仿我想要的回应?
答案 0 :(得分:4)
此测试通过。我添加了评论以显示每个步骤指示的内容:
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.
}
答案 1 :(得分:0)
工作正常。
1*getName()>>"Hello"
1*getName()>>"Hello Java"
第一次调用即获得"Hello"
。
获得"Hello Java
“