在使用 Mockito 进行方法调用时拦截对象

2022-01-08 00:00:00 mocking mockito java

我有一个类似 void 方法的模拟类

I've a mocked class with a void method like

public class Mock {
    public void method(String string) {
        // doSomething
    }
}

我不关心这个方法的作用,但我想发送字符串.

I don't care about what this method does but I would like to get the String sent.

这个字符串实际上是一个 JSON 格式的对象,我正在测试的方法是根据最初发送的字符串修改这个对象(假设是非常随机的).

This String is actually an object in a JSON format, and the method that I'm testing is modifying this object depending on the String originally sent (quite random let's say).

method(String json) {
    Object obj = unparse(json);
    obj.setRandomValue(random);
    String parsed = parse(obj);
    Mock.method(parsed);
}

我只是想看看之前为空的randomValue"是否在方法调用后实际上设置为随机数.

I would like just to see if the "randomValue", previously null, is actually set with the random after the method invocation.

最好的办法是截取 json,解析它并检查对象.

The best would be to intercept the json, parse it and check the object.

推荐答案

您正在寻找一个 ArgumentCaptor:

You are looking for an ArgumentCaptor:

  Mock mock =  Mockito.mock(Mock.class);
  ArgumentCaptor<String> captor = ArgumentCaptor.forClass(String.class);
  mock.method("input");
  Mockito.verify(mock).method(captor.capture());
  String actualValue = captor.getValue();

相关文章