如何在Java单元测试中模拟HttpServletRequest
getResourceAsStream
?我正在使用它来阅读Servlet请求中的资源文件。
HttpServletRequest.getSession().getServletContext().getResourceAsStream()
我正在使用org.mockito.Mock
来模拟HttpServletRequest
。
您需要做很多模拟。我建议使用注释:
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
}
}
@Before
public void setup() {
MockHttpServletRequest servletRequest = new MockHttpServletRequest();
servletRequest.setRequestURI("/Turmo/");
RequestContextHolder.setRequestAttributes(new ServletRequestAttributes(servletRequest));
}