使用PowerMockito模拟装饰的流

时间:2016-02-29 12:45:48

标签: io inputstream powermock outputstream wrapping

所以我有一个类,它在构造函数中接受一个OutputStream,并在方法中从它创建一个PrintWriter。问题是如何让这个PrintWriter验证它?

Example public Class(OutputStream output) {}
public void foo() {
  PrintWriter writer = new PrintWriter(output);
}

我尝试做的是:

PrintWriter writer = PowerMockito.mock(PrintWriter.class)
PowerMockito
    .whenNew(PrintWriter.class)
    .withArguments(output)
    .thenReturn(writer);

但是我知道没有与这位作家的相互作用。任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:0)

如果您提供了带有PowerMock配置的完整代码段,那将会更好。然后我可以帮助你并提供建议,现在我可能只会猜到可能出错的地方,但我正在尝试:

PrintWriter有几个构造函数可以接受OutputStream而PowerMock有一个缺陷,它可能会错误地猜测哪个构造函数被模拟,当你在类重载构造函数时只传递参数时。

也可能是常见的错误,您还没有添加创建PrintWriter@PrepareForTest的实例的类。

所以,基于我的假设案例的实例:

public class PrintWriterCreator {

    private final PrintWriter printWriter;

    public PrintWriterCreator(OutputStream outputStream) {
        this.printWriter = new PrintWriter(outputStream);
    }

    public void write(String message){
        printWriter.write(message);
    }
}

测试类:

@RunWith(PowerMockRunner.class)
@PrepareForTest({PrintWriter.class, PrintWriterCreator.class})
public class PrintWriterCreatorTest {


    @Mock
    private OutputStream outputStream;

    @Mock
    private PrintWriter printWriterMock;

    private PrintWriterCreator printWriterCreator;


    @Before
    public void setUp() throws Exception {

        whenNew(PrintWriter.class).withParameterTypes(OutputStream.class).withArguments(eq(outputStream)).thenReturn
                                                                                                       (printWriterMock);

        printWriterCreator = new PrintWriterCreator(outputStream);
    }

    @Test
    public void testWrite() throws Exception {
        String message = "someMessage";
        printWriterCreator.write(message);

        verifyNew(PrintWriter.class).withArguments(outputStream);

        verify(printWriterMock).write(eq(message));
    }


}