我有该类的实现:
public class testImpl{
public void method(Object a){
Object obj = new Object();
PrintWritter printW = a.getWriter();
printW.append(obj.toString());
}
}
在printW执行方法“ append”时,如何捕获“ obj”的值?
答案 0 :(得分:2)
因此,您有两个选择:
模拟PrintWriter
并在调用obj.toString()
时捕获append
。但是,这只会为您提供String
的{{1}}表示,而不是实际的对象,例如:
Object
使用PrintWriter mockWriter = Mockito.mock(PrintWriter.class);
Object mockA = Mockito.mock(Object.class);
Mockito.when(mockA.getWriter()).thenReturn(mockWriter);
ArgumentCaptor<String> argument = ArgumentCaptor.forClass(String.class);
verify(mockWriter).append(argument.capture());
String result = argument.getValue();
并模拟本地变量类的构造函数,例如:
PowerMockito
您将必须用Object mockObject = Mockito.mock(Object.class);
PowerMockito.whenNew(Object.class).withNoArguments().thenReturn(mockObject);
注释junit类。