【问题标题】:How to mock FileInputStream and FileOutputStrem consrtuctors on Android Unit Test?如何在 Android 单元测试中模拟 FileInputStream 和 FileOutputStrem 构造函数?
【发布时间】:2020-06-25 12:33:40
【问题描述】:

我有跟随场景:

  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:How to mock FileInputStream and other *Streams 它对我不起作用

【问题讨论】:

    标签: java android mockito powermockito easymock


    【解决方案1】:

    替换就解决了

    @PrepareForTest({
            FileInputStream.class
    })
    

    实例

    @PrepareForTest({
            A.class
    })
    

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

    【讨论】:

      猜你喜欢
      • 2021-09-29
      • 2019-03-23
      • 1970-01-01
      • 2015-09-18
      • 2014-05-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多