欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Java如何Mock FileInputStream問題

 更新時(shí)間:2023年09月21日 14:38:28   作者:JonTang  
這篇文章主要介紹了Java如何Mock FileInputStream問題,具有很好的參考價(jià)值,希望對大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教

Java如何Mock FileInputStream

1. 最近在寫UT(單元測試) 的過程

遇到需要 Mock 出 FileInputStream 的情況,在這里分享一下自己的解決方案。

需要 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. 如果需要實(shí)際讀取一個(gè)文件時(shí)

例如要讀取 resources 目錄下的某個(gè)文件,可以將代碼修改為如下所示:

@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:補(bǔ)充一下自己的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>

Java mockito mock InputStream

方案

使用apache commons的IOUtils直接構(gòu)造一個(gè)基于String的InputStream,一些文本傳輸相關(guān)的測試的場景里非常實(shí)用。

Process mockProcess = mock(Process.class);
InputStream errorStream = org.apache.commons.io.IOUtils.toInputStream("error message", "UTF-8");
when(mockProcess.getErrorStream()).thenReturn(errorStream);

總結(jié)

以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。

相關(guān)文章

最新評論