Spring Boot中Excel转JSON服务类的JUnit测试实现咨询
Spring Boot Excel转JSON服务单元测试实现指导
原有测试代码存在的问题
- Mockito默认不支持mock
Files这类JDK静态方法,你现有测试的静态方法mock逻辑无法生效 getSheetDataList、getJSONStringFromList是私有方法,不能直接被Mockito mock- 下标逻辑错误:sheet总数为1时调用
getSheetAt(1)会触发数组越界,Excel sheet下标从0开始 - 服务类全局捕获了所有异常,仅打印日志不向外抛出,空文件测试的异常预期永远无法触发
真实Excel文件测试方案实现
第一步:准备测试资源
在项目src/test/resources目录下新建excel文件夹,放入2个测试文件:
test_normal.xlsx:第一行表头为Address、Name,第二行填充测试数据Bangalore、tejatest_empty.xlsx:无任何内容的空Excel文件
第二步:编写测试代码
Spring自带MockMultipartFile可以直接将本地资源文件转换为服务层需要的MultipartFile对象,无需复杂mock逻辑,完整测试类如下:
import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import org.mockito.InjectMocks; import org.mockito.junit.jupiter.MockitoExtension; import org.springframework.mock.web.MockMultipartFile; import static org.junit.jupiter.api.Assertions.assertEquals; @ExtendWith(MockitoExtension.class) public class UploadServiceTest { @InjectMocks private UploadService uploadService; // 测试正常Excel文件转换逻辑 @Test void testNormalExcelToJson() throws Exception { MockMultipartFile testFile = new MockMultipartFile( "file", "test_normal.xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", getClass().getResourceAsStream("/excel/test_normal.xlsx") ); String result = uploadService.creteJSONFromExcel(testFile); // 按你的服务逻辑,会自动生成id字段且返回JSON数组 String expected = "[{\"Address\":\"Bangalore\",\"Name\":\"teja\",\"id\":\"1\"}]"; assertEquals(expected, result); } // 测试空Excel文件逻辑 @Test void testEmptyExcel() throws Exception { MockMultipartFile emptyFile = new MockMultipartFile( "file", "test_empty.xlsx", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", getClass().getResourceAsStream("/excel/test_empty.xlsx") ); String result = uploadService.creteJSONFromExcel(emptyFile); // 你现有服务逻辑捕获了异常返回空字符串,此处验证返回空即可 assertEquals("", result); } }
可选优化点
- 如果需要验证空文件抛出异常的逻辑,修改服务类的异常处理逻辑,不要全局捕获异常,改为抛出自定义运行时异常,再在测试中用
assertThrows验证异常 - 如需兼容xls格式,修改
MockMultipartFile的contentType为application/vnd.ms-excel即可 - 注意你的服务方法名
creteJSONFromExcel存在拼写错误,建议修正为createJSONFromExcel
内容的提问来源于stack exchange,提问作者Nikhith
相关产品推荐
相关产品推荐

