我具有类实现:
public class testImpl{
public void method(Object a){
Object obj = new Object();
PrintWritter printW = a.getWriter();
printW.append(obj.toString());
}
}
printw执行方法"附加"时,如何捕获" obj"的值?
所以,您有两个选择:
-
模拟
PrintWriter
并在调用append
时捕获obj.toString()
。但是,这只会为您提供Object
的String
表示,而不是实际对象,例如: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);
您必须用
@PrepareForTest(Object.class)
来注释Junit类。