当我无法使用Mockito.when()时,如何在PowerMockito中使用doReturn模式来模拟静态方法?
我想测试以下静态方法:
public static PrintWriter openWriter(File file, Charset charset, boolean autoflush) throws FileNotFoundException {
return openWriterHelper(new FileOutputStream(file), charset, autoflush);
}
这是我的testMethod:
@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);
}
问题是我无法在调用when时调用openWriterHelper,因为该方法在传递模拟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);
}
答案 0 :(得分:4)
尝试
doReturn(expected).when(IOHelper.class, "openWriterHelper", file, charset, true);
或
when(IOHelper.class, "openWriterHelper", file, charset, true).thenReturn(expected);
答案 1 :(得分:3)
替换这行代码:
when(IOHelper.openWriterHelper(fos, charset, true)).thenReturn(expected);
带
doReturn(expected).when(IOHelper.class);
IOHelper.openWriter(fos,charset, true);