所以我有一个类,它在构造函数中获取一个输出流,并在方法中从中创建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);
但是我知道与这位作家没有任何互动。任何帮助将不胜感激。
如果您提供包含 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));
}
}