問題描述
我有一個(gè)類似 void 方法的模擬類
I've a mocked class with a void method like
public class Mock {
public void method(String string) {
// doSomething
}
}
我不關(guān)心這個(gè)方法的作用,但我想發(fā)送字符串.
I don't care about what this method does but I would like to get the String sent.
這個(gè)字符串實(shí)際上是一個(gè) JSON 格式的對象,我正在測試的方法是根據(jù)最初發(fā)送的字符串修改這個(gè)對象(假設(shè)是非常隨機(jī)的).
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"是否在方法調(diào)用后實(shí)際上設(shè)置為隨機(jī)數(shù).
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.
推薦答案
您正在尋找一個(gè) 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();
這篇關(guān)于在使用 Mockito 進(jìn)行方法調(diào)用時(shí)攔截對象的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!