单元测试中,模拟IO流读写时的close()方法抛出异常

场景: 对IOException类进行单元测试,覆盖率达到100%

目标代码:

public static String getMD5ValueOfFile(InputStream fileStream) {
		MessageDigest digest = null;
		try {
			digest = MessageDigest.getInstance("MD5");
			// 定义一个字节数组
			byte[] buffer = new byte[1024];
			// 定义一个length变量
			int length = -1;
			while ((length = fileStream.read(buffer, 0, buffer.length)) != -1) {
				digest.update(buffer, 0, length);// 更新摘要
			}

		} catch (Exception e) {
			e.printStackTrace();
			return "error";
		} finally {// 释放资源
			if (fileStream != null) {
				try {
					fileStream.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
}

测试类:

@Test(expected = IOException.class)
public void testGetMD5ValueOfFileCloseException() throws Exception {
        FileInputStream inputStream = mock(FileInputStream.class);
        byte[] buffer = new byte[1024];
        PowerMockito.when(inputStream,method(FileInputStream.class,"close")).withNoArguments().thenThrow(new IOException());
        when(inputStream.read(buffer, 0, buffer.length)).thenReturn(-1);
        MD5Util.getMD5ValueOfFile(inputStream);
}

 

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