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