使用 void return 类型链接来自 spock 存根的副作用

Chaining side effects from spock stub with void return type

我正在尝试测试以下(人为设计的)代码,它会进行调用,如果调用失败则尝试重试一次。

 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]

如何模拟我想要的回应?

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

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*getName()>>"Hello"
1*getName()>>"Hello Java"

第一次调用我得到 "Hello"。 第二次调用我得到 "Hello Java"