jeudi 20 août 2015

java servlet test with different URLs

I want to test my Servlet with different incoming URLs. I tried to use Mockito to test if specific function was called:

package servlet;

import blabla;

@RunWith(MockitoJUnitRunner.class)
@ContextConfiguration(locations = {"classpath:application-context-test.xml"})
public class MainServletTest extends TestCase{

    @Autowired
    private Categories categories;

    private MockHttpServletRequest request = new MockHttpServletRequest();

    @Mock
    private HttpServletResponse response;

    @Mock
    private HttpSession session;

    @Mock
    private RequestDispatcher rd;

    @Test
    public void testCategories() throws ServletException, IOException {
        // given
        request.setServerName("localhost");//here I try to change incoming URL
        request.setRequestURI("/test/categories");//here I try to change incoming URL
        HttpServletRequest req = spy(request);//???
        //when
        new MainServlet().doGet(req, response);


        //then
        verify(req).setAttribute("categories", categories.getContainer());//here try to check if this method is called
    }
}

Here I try to change incoming url and check if specific attribute was set for incoming request. Since req is not Mock object but MockHttpServletRequest object - this code does not work. Any ideas?

Aucun commentaire:

Enregistrer un commentaire