【发布时间】:2012-03-31 23:19:55
【问题描述】:
从PowerMock homepage 上的示例中,我看到了以下使用 Mockito 部分模拟私有方法的示例:
@RunWith(PowerMockRunner.class)
// We prepare PartialMockClass for test because it's final or we need to mock private or static methods
@PrepareForTest(PartialMockClass.class)
public class YourTestCase {
@Test
public void privatePartialMockingWithPowerMock() {
PartialMockClass classUnderTest = PowerMockito.spy(new PartialMockClass());
// use PowerMockito to set up your expectation
PowerMockito.doReturn(value).when(classUnderTest, "methodToMock", "parameter1");
// execute your test
classUnderTest.execute();
// Use PowerMockito.verify() to verify result
PowerMockito.verifyPrivate(classUnderTest, times(2)).invoke("methodToMock", "parameter1");
}
但是,当我们希望模拟的私有方法是静态的时,这种方法似乎不起作用。我希望创建以下类的部分模拟,并模拟 readFile 方法:
package org.rich.powermockexample;
import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.List;
import static com.google.common.io.Files.readLines;
public class DataProvider {
public static List<String> getData() {
List<String> data = null;
try {
data = readFile();
} catch (IOException e) {
e.printStackTrace();
}
return data;
}
private static List<String> readFile() throws IOException {
File file = new File("/some/path/to/file");
List<String> lines = readLines(file, Charset.forName("utf-8"));
return lines;
}
}
请有人告诉我这是如何实现的?
【问题讨论】:
-
为什么呢?换句话说,你不能通过仅模拟 getData 来模拟什么?
-
我可以 - 但我想看看是否可以使用 PowerMock 在部分模拟中处理私有静态方法。
-
哦。我必须查找机制,但是AFAIK是的,通过字节码操作,就像你可以模拟或替换构造函数一样。
-
同意 - 我认为这至少是可能的,但无法从文档中找到执行此操作的方法。
标签: java unit-testing mockito powermock