在我的Spring项目中,我有测试,我想存根一个链式函数调用。
要测试的函数调用是:
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
?
发布于 2019-08-06 08:29:34
Afaik @MockBean
不创建deep stub mocks
,这意味着不支持模拟调用的链接。
您的问题是mockedRequest.getReader()
返回null。
您可以切换到只使用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);
https://stackoverflow.com/questions/57378790
复制