JUnit测试Java WebFlux上传服务时遭遇NullPointerException求助
解决FilePart Mock导致的NullPointerException问题
问题根源
你当前只Mock了FilePart的filename()方法,但没有Mockcontent()方法,调用filePart.content()时会返回null,后续调用map操作自然抛出NullPointerException。
正确Mock方式
需要MockfilePart.content(),让它返回一个包含模拟DataBuffer的Flux,具体操作如下:
- 模拟DataBuffer:创建包含测试数据的
DataBuffer,模拟文件内容 - Mock content()方法:让
filePart.content()返回包含该DataBuffer的Flux
完整测试代码示例
@Test void testing_1() throws UnsupportedEncodingException { // 1. 准备测试用的文件内容字节数组 String testContent = "测试内容,123\n第二行数据,456"; byte[] contentBytes = testContent.getBytes(StandardCharsets.UTF_8); // 2. Mock DataBuffer,模拟可读字节数据 DataBuffer mockDataBuffer = Mockito.mock(DataBuffer.class); Mockito.when(mockDataBuffer.readableByteCount()).thenReturn(contentBytes.length); Mockito.when(mockDataBuffer.read(Mockito.any(byte[].class))).thenAnswer(invocation -> { byte[] dest = invocation.getArgument(0); System.arraycopy(contentBytes, 0, dest, 0, contentBytes.length); return contentBytes.length; }); // 3. Mock FilePart的content()方法,返回包含模拟DataBuffer的Flux FilePart filePart = BDDMockito.mock(FilePart.class); BDDMockito.given(filePart.filename()).willReturn("resources/ejemplo.csv"); BDDMockito.given(filePart.content()).willReturn(Flux.just(mockDataBuffer)); // 4. Mock repo方法 Mockito.when(repo.metodo(any())).thenReturn("Abcd"); // 5. 调用服务方法并验证结果 Flux<String> result = service.importData(filePart); StepVerifier.create(result) .expectNextCount(1) // 根据实际业务逻辑调整预期数量 .verifyComplete(); }
服务类代码优化提示
你的服务类中第二个map(t -> {})是空实现,会导致编译报错,建议补充字节数组转字符串的逻辑,示例如下:
public Flux<String> importData(FilePart filePart) { return filePart.content() .map(dataBuffer -> { byte[] bytes = new byte[dataBuffer.readableByteCount()]; dataBuffer.read(bytes); DataBufferUtils.release(dataBuffer); return bytes; }) .map(bytes -> new String(bytes, StandardCharsets.UTF_8)); // 补充字节转字符串逻辑 }
内容的提问来源于stack exchange,提问作者ProgrammerGirl
相关产品推荐
相关产品推荐

