2017-09-21 1 views
1

Comment faire pour simuler HttpServletRequestgetResourceAsStream dans un test d'unité Java? Je l'utilise pour lire un fichier de ressources à partir d'une requête de servlet.Java Test Unit Mock HttpServletRequest getResourceAsStream

HttpServletRequest.getSession().getServletContext().getResourceAsStream()

J'utilise org.mockito.Mock à Mock HttpServletRequest.

Répondre

2

Il y a pas mal de moquerie à faire. Je suggère d'utiliser des 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 

    } 
}