Java 如何 Mock FileInputStream

前言:

        最近在写 UT(单元测试) 的过程中,遇到需要 Mock 出 FileInputStream 的情况,在这里分享一下自己的解决方案。

  1. 需要 Mock 的类:
    public class Class1 {
    
        public Class1() { }
    
        public boolean method1() {
            try {
                FileInputStream fileInputStream = new FileInputStream("file.txt");
            } catch (FileNotFoundException e) {
                e.printStackTrace();
                return false;
            }
            return true;
        }
    
    }

  2. 测试类如下:
    @RunWith(PowerMockRunner.class)
    @PrepareForTest(Class1.class)
    public class Class1Test {
    
        @Test
        public void method1Test() throws Exception {
    
            Class1 class1 = new Class1();
    
            FileInputStream fileInputStreamMock = mock(FileInputStream.class);
            whenNew(FileInputStream.class).withAnyArguments().thenReturn(fileInputStreamMock);
    
            boolean expected = true;
            boolean actual = class1.method1();
    
            assertEquals(expected, actual);
    
        }
    
    }

   注意:

        在单元测试中我使用了 @PrepareForTest(Class1.class),而没有使用 @PrepareForTest(FileInputStream.class)

        3. 如果需要实际读取一个文件时,例如要读取 resources 目录下的某个文件,可以将代码修改为如下所示:

@RunWith(PowerMockRunner.class)
@PrepareForTest(Class1.class)
public class Class1Test {

    @Test
    public void method1Test() throws Exception {

        Class1 class1 = new Class1();

        String path = new File(getClass().getClassLoader().getResource("file.txt").getFile()).getCanonicalPath();
        FileInputStream fileInputStream = new FileInputStream(path);

        whenNew(FileInputStream.class).withAnyArguments().thenReturn(fileInputStreamMock);

        boolean expected = true;
        boolean actual = class1.method1();

        assertEquals(expected, actual);

    }

}

PS:补充一下自己的pom依赖

<dependency>
        <groupId>org.powermock</groupId>
        <artifactId>powermock-module-junit4</artifactId>
        <version>1.7.4</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.powermock</groupId>
        <artifactId>powermock-api-mockito</artifactId>
        <version>1.7.4</version>
        <scope>test</scope>
    </dependency>
</dependencies>
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

JonTang

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值