在我的 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
在存根链接函数返回时如何摆脱这种情况?
Afaik@MockBean
不 create deep stub mocks
,这意味着不支持链接模拟调用。
你的问题是mockedRequest.getReader()
返回空值。
您可以只切换到使用 mockito
(如果您不需要任何自动装配和诸如此类的东西/
imho 在这种情况下似乎不相关HttpServletRequest
)
@Mock(answer = Answers.RETURNS_DEEP_STUBS)
否则,您必须为每个调用的方法提供不同的模拟。
Stream stream = Mockito.mock(Stream.class);
when(stream.collect(Collectors.joining(System.lineSeparator()))).thenReturn("FooBarData");
BufferedReader reader = Mockito.mock(BufferedReader.class);
when(reader.lines()).thenReturn(stream);
when(mockedRequest.getReader()).thenReturn(reader)
模拟流非常难看,因此您可能希望用提供匹配答案的真实流替换该部分。
例如:
Stream<String> stream = Stream.of("FooBarData");
when(reader.lines()).thenReturn(stream);
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句