Question

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);

}

Was it helpful?

Solution 2

Replace this line of code:

when(IOHelper.openWriterHelper(fos, charset, true)).thenReturn(expected);

with

 doReturn(expected).when(IOHelper.class);
 IOHelper.openWriter(fos,charset, true);

OTHER TIPS

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top