Reputation: 6606
How to I use the doReturn pattern in PowerMockito to mock a static method when I can't use Mockito.when()?
I want to test the following static method:
public static PrintWriter openWriter(File file, Charset charset, boolean autoflush) throws FileNotFoundException {
return openWriterHelper(new FileOutputStream(file), charset, autoflush);
}
This is my 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);
}
The problem is that I can't put openWriterHelper in a call to when, because the method will raise an exception when passed a mock OutputStream.
If it matters, this is the code for 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);
}
Upvotes: 12
Views: 28892
Reputation: 2387
try
doReturn(expected).when(IOHelper.class, "openWriterHelper", file, charset, true);
or
when(IOHelper.class, "openWriterHelper", file, charset, true).thenReturn(expected);
Upvotes: 7
Reputation: 6606
Replace this line of code:
when(IOHelper.openWriterHelper(fos, charset, true)).thenReturn(expected);
with
doReturn(expected).when(IOHelper.class);
IOHelper.openWriter(fos,charset, true);
Upvotes: 3