简体   繁体   中英

Problem with the scenario writing in Mockito

I am writing the unit test for my class using JUnit and Mockito. For a particular test I have Mocked httpServletRequest object but instead of returning Hello it is throwing NullPointerException can anyone tell me how to write the scenario correctly.

HttpServletRequest httpServletRequest = mock(HttpServletRequest.class);

// Trying to fetch the Request Body     

when(httpServletRequest.getReader().lines().collect(Collectors.joining(System.lineSeparator()))).thenReturn
        ("Hello");

To mock a class I would use org.mockito.Mockito.mock()

HttpServletRequest httpServletRequest = org.mockito.Mockito.mock(HttpServletRequest.class);

then, use when for the scenario.

I hope to be helpful.

You are mocking HttpServletRequest. So httpServletRequest is not null, but httpServletRequest.getReader() is. Calling lines() then causes NPE.

Want do you actually want to achieve?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM