当我不能使用 Mockito.when() 时,如何使用 PowerMockito 中的 doReturn 模式来模拟静态方法?
我想测试以下静态方法:
public static PrintWriter openWriter(File file, Charset charset, boolean autoflush) throws FileNotFoundException {
return openWriterHelper(new FileOutputStream(file), charset, autoflush);
}
这是我的测试方法:
@Test
public void testOpenWriter_file_charset_autoflush() throws Throwable {
Charset charset = mock(Charset.class);
PrintWriter expected = mock(PrintWriter.class);
File file = mock(File.class);
FileOutputStream fos = mock(FileOutputStream.class);
spy(IOHelper.class);
whenNew(FileOutputStream.class).withArguments(file).thenReturn(fos);
when(IOHelper.openWriterHelper(fos, charset, true)).thenReturn(expected);
PrintWriter observed = IOHelper.openWriter(file, charset, true);
assertEquals(expected, observed);
verifyStatic();
IOHelper.openWriterHelper(fos, charset, true);
}
问题是我不能将 openWriterHelper 放在对 when 的调用中,因为该方法在传递模拟 OutputStream 时会引发异常。
如果重要的话,这是 openWriterHelper 的代码:
public static PrintWriter openWriterHelper(OutputStream stream, Charset charset,
boolean autoflush) {
return new PrintWriter(new java.io.BufferedWriter(
new java.io.OutputStreamWriter(stream, charset)), autoflush);
}