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依赖


        org.powermock
        powermock-module-junit4
        1.7.4
        test
    
    
        org.powermock
        powermock-api-mockito
        1.7.4
        test
    

你可能感兴趣的:(Java,java,单元测试)