如何在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
}
}
关于java - Java单元测试模拟HttpServletRequest getResourceAsStream,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/46342796/