12

当我不能使用 Mockito.when() 时,如何使用 PowerMockito 中的 doReturn 模式来模拟静态方法?

我想测试以下静态方法:

public static PrintWriter openWriter(File file, Charset charset, boolean autoflush) throws FileNotFoundException {
      return openWriterHelper(new FileOutputStream(file), charset, autoflush);
   }

这是我的测试方法:

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

}

问题是我不能将 openWriterHelper 放在对 when 的调用中,因为该方法在传递模拟 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);

}

4

2 回答 2

5

尝试

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

于 2014-05-05T14:58:17.670 回答
3

替换这行代码:

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

 doReturn(expected).when(IOHelper.class);
 IOHelper.openWriter(fos,charset, true);
于 2011-09-16T15:26:09.860 回答