我有以下场景:
public class A {
public void TestIn() throws FileNotFoundException {
FileInputStream in = new FileInputStream("myFile");
FileOutputStream out = new FileOutputStream("out");
doSomeThing();
}
}
我尝试使用以下代码库对其进行测试:
@RunWith(PowerMockRunner.class)
@PrepareForTest({
FileInputStream.class
})
public class ATest {
@Test
public void testA() throws Exception {
final FileInputStream fileInputStreamMock = PowerMockito.mock(FileInputStream.class);
PowerMockito.whenNew(FileInputStream.class).withArguments(Matchers.anyString())
.thenReturn(fileInputStreamMock);
A a = new A();
a.TestIn();
}
}
以下异常是抛出:
java.io.FileNotFoundException: myFile (The system cannot find the file specified)
at java.io.FileInputStream.open0(Native Method)
at java.io.FileInputStream.open(FileInputStream.java:195)
at java.io.FileInputStream.<init>(FileInputStream.java:138)
at java.io.FileInputStream.<init>(FileInputStream.java:93)
PS:如何模拟文件输入流和其他*流它对我不起作用
已解决,只需替换
@PrepareForTest({
FileInputStream.class
})
的实例
@PrepareForTest({
A.class
})
根据 https://www.hellojava.com/a/41893.html