Mockito能否捕获实现中声明的变量的参数?

时间:2019-02-14 08:56:07

标签: java unit-testing mockito verify

我有该类的实现:

public class testImpl{
  public void method(Object a){
    Object obj = new Object();
    PrintWritter printW = a.getWriter();
    printW.append(obj.toString());
  }
}

在printW执行方法“ append”时,如何捕获“ obj”的值?

1 个答案:

答案 0 :(得分:2)

因此,您有两个选择:

  1. 模拟PrintWriter并在调用obj.toString()时捕获append。但是,这只会为您提供String的{​​{1}}表示,而不是实际的对象,例如:

    Object
  2. 使用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类。