java - 如何在 Android 单元测试中模拟 FileInputStream 和 FileOutputStrem 构造函数?
问题描述
我有以下场景:
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:如何模拟 FileInputStream 和其他 *Streams它对我不起作用
解决方案
它已解决只需更换
@PrepareForTest({
FileInputStream.class
})
的实例
@PrepareForTest({
A.class
})
推荐阅读
- ms-access - 访问表单的动态组合框问题
- android - 如果键在另一个对象内,如何使用 Retrofit 解析 Json
- javascript - JavaScript:提取数组中每个字符串的第一个字母?
- ios - three.js fontloader 在 ios 上不起作用
- sql - 如何在sql中将dd-mm-yyyy转换为DD-MON-yyyy
- hyperledger-fabric - 使用单独的 configtx.yaml 文件按顺序生成 genesis.block 和 channel.tx 时出错
- ios - 使用 Jenkins for iOS 设置构建 fastlane
- php - woocommerce 条件字段
- java - 带有 CheckedTextView 的列表视图无法正常工作
- php - PHP 时区。为什么偏移量为零?