使用doReturn部分模拟PowerMockito的静态方法

时间:2011-09-12 17:46:43

标签: mockito powermock

当我无法使用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);

}

2 个答案:

答案 0 :(得分:4)

尝试

doReturn(expected).when(IOHelper.class, "openWriterHelper", file, charset, true);

when(IOHelper.class, "openWriterHelper", file, charset, true).thenReturn(expected);

参见以下样本: 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

答案 1 :(得分:3)

替换这行代码:

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

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