首页 > 解决方案 > 如何在 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它对我不起作用

标签: javaandroidmockitopowermockitoeasymock

解决方案


它已解决只需更换

@PrepareForTest({
        FileInputStream.class
})

的实例

@PrepareForTest({
        A.class
})

根据https://www.hellojava.com/a/41893.html


推荐阅读