【发布时间】:2025-11-28 12:00:01
【问题描述】:
在我的 Spring Boot 项目中,我有测试,我想存根链式函数调用。
要测试的函数调用是:
private String sniffPayload(HttpServletRequest request) throws IOException {
return request.getReader().lines().collect(Collectors.joining(System.lineSeparator()));
}
在我的单元测试中,我使用 Mockito 来模拟 HttpServletRequest:
import org.springframework.boot.test.mock.mockito.MockBean;
@MockBean
private HttpServletRequest mockedRequest;
然后,在我的测试函数中:
@Test
void testMyFunction() throws Exception {
// I try to stub the function return
// But get NullPointerException at runtime
when(mockedRequest.getReader().lines().collect(Collectors.joining(System.lineSeparator()))).thenReturn("FooBarData");
...
}
当我运行测试时,我得到了 NullPointerException 用于执行存根的代码行 when(mockedRequest.getReader().lines().collect(Collectors.joining(System.lineSeparator()))).thenReturn("FooBarData");
为什么?我怎样才能在存根链接函数返回时摆脱这个NullPointerException?
【问题讨论】:
标签: unit-testing spring-boot mockito