Java单元测试模拟httpservletrequest getResourCeasStream



如何在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));
    }

相关内容

  • 没有找到相关文章

最新更新