Issue
How to mock HttpServletRequest
getResourceAsStream
in a Java unit test? I am using it to read a resource file from a servlet request.
HttpServletRequest.getSession().getServletContext().getResourceAsStream()
I am using org.mockito.Mock
to Mock HttpServletRequest
.
Solution
There is quite a bit of mocking you need to do. I would suggest using annotations:
import static org.mockito.Mockito.when;
public class TestClass{
@Mock
private HttpServletRequest httpServletRequestMock;
@Mock
private HttpSession httpsSessionMock;
@Mock
private ServletContext servletContextMock;
@Before
public void init(){
MockitoAnnotations.initMocks(this);
}
@Test
public void test(){
// Arrange
when(httpServletRequestMock.getSession()).thenReturn(httpSessionMock);
when(httpSessionMock.getServletContext()).thenReturn(servletContextMock);
InputStream inputStream = // instantiate;
when(servletContextMock.getResourceAsStream()).thenReturn(inputStream);
// Act - invoke method under test with mocked HttpServletRequest
}
}
Answered By - Maciej Kowalski