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);
}
Use PowerMockito. mockStatic() for mocking class with static methods. Use PowerMockito. verifyStatic() for verifying mocked methods using Mockito.
Of course you can – and probably will – use Mockito and PowerMock in the same JUnit test at some point of time.
To use PowerMock with Mockito, we need to apply the following two annotations in the test: @RunWith(PowerMockRunner. class): It is the same as we have used in our previous examples. The only difference is that in the previous example we have used MockitoUnitRunner.
The parameter of doReturn is Object unlike thenReturn . So, there is no type checking in the compile time. When the type is mismatched in the runtime, there would be an WrongTypeOfReturnValue execption. doReturn(true).
try
doReturn(expected).when(IOHelper.class, "openWriterHelper", file, charset, true);
or
when(IOHelper.class, "openWriterHelper", file, charset, true).thenReturn(expected);
see samples in: http://code.google.com/p/powermock/source/browse/trunk/modules/module-test/powermockito/junit4/src/test/java/samples/powermockito/junit4/partialmocking/StaticPartialMockingTest.java?r=1366
Replace this line of code:
when(IOHelper.openWriterHelper(fos, charset, true)).thenReturn(expected);
with
doReturn(expected).when(IOHelper.class);
IOHelper.openWriter(fos,charset, true);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With