問題描述
我有一個類似 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();
這篇關于在使用 Mockito 進行方法調用時攔截對象的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!