文件处理的单元测试
最近开发过程中经常对文件进行处理,开发过程比较顺利,但是单元测试的时候总是会遇到问题,总计了下文件处理过程中单元测试的几个问题
1. mock一个函数内新建的File类
整体代码如下所示:
public static byte[] getBytesByFile(String filePath) {
try {
File file=new File(filePath);
//获取输入流
FileInputStream fis = new FileInputStream(file);
//新的 byte 数组输出流,缓冲区容量1024byte
ByteArrayOutputStream bos = new ByteArrayOutputStream(1024);
//缓存
byte[] b = new byte[1024];
int n;
while ((n = fis.read(b)) != -1) {
bos.write(b, 0, n);
}
fis.close();
//改变为byte[]
byte[] data = bos.toByteArray();
//
bos.close();
return data;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
其中遇到了
File file=new File(filePath);
单元测试我们希望能够摆脱环境依赖,所以我们避免使用一个绝对路径作为输入,为此mock了一个虚拟的File。
File fileMock = Mockito.mock(File.class);
PowerMockito.whenNew(File.class).withAnyArguments().thenReturn(fileMock);
2. FileInputStream的mock
功能函数中除了新建一个File之外还新建了一个FileInputStream,mock方式如下
FileInputStream fileInputStreamMock = Mockito.mock(FileInputStream.class);
PowerMockito.whenNew(FileInputStream.class).withAnyArguments().thenReturn(fileInputStreamMock);
但是这样会报FileNotFoundException,所以需要在测试类的类名上加上
@PrepareForTest(FileByteArrayTransferUtil.class)
解决方法来自http://www.hellojava.com/a/41893.html
整个方法的单元测试代码如下
@RunWith(PowerMockRunner.class)
@PrepareForTest(FileByteArrayTransferUtil.class)
public class FileByteArrayTransferUtilTest {
@InjectMocks
FileByteArrayTransferUtil fileByteArrayTransferUtil;
@Test
public void getBytesByFile() throws Exception {
File fileMock = Mockito.mock(File.class);
PowerMockito.whenNew(File.class).withAnyArguments().thenReturn(fileMock);
FileInputStream fileInputStreamMock = Mockito.mock(FileInputStream.class);
PowerMockito.whenNew(FileInputStream.class).withAnyArguments().thenReturn(fileInputStreamMock);
Mockito.when(fileInputStreamMock.read(Mockito.any())).thenReturn(-1);
byte[] bytesByFile = FileByteArrayTransferUtil.getBytesByFile("");
assertNotNull(bytesByFile);
}
}