Java如何Mock FileInputStream问题
作者:JonTang
这篇文章主要介绍了Java如何Mock FileInputStream问题,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教
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. 如果需要实际读取一个文件时
例如要读取 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>Java mockito mock InputStream
方案
使用apache commons的IOUtils直接构造一个基于String的InputStream,一些文本传输相关的测试的场景里非常实用。
Process mockProcess = mock(Process.class);
InputStream errorStream = org.apache.commons.io.IOUtils.toInputStream("error message", "UTF-8");
when(mockProcess.getErrorStream()).thenReturn(errorStream);总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。
