Expand my Community achievements bar.

How to write the unit test for the given SlingServlet.

Avatar

Level 2

Hello

 

I have a doGet servlet method like below

 

@reference
private transient ProductXfQueryService productsService;

protected void doGet(@Nonnull SlingHttpServletRequest request, @Nonnull SlingHttpServletResponse response){
    response.setContentType("application/json");
        PrintWriter out = response.getWriter();

        String id = request.getParameter(CAT_ID_PARAM);
        String variant = request.getParameter("variant");
        Session session = request.getResourceResolver().adaptTo(Session.class);

        ProductCategory category = this.productsService.getCategory(id, variant, session);

        if (category == null) {
            response.setStatus(SC_NOT_FOUND);
            out.write("{ \"error\": \"Could not find category for given id.\" }");
            return;
        }

        //some code below neglect it...

}

 

so I write the testcases like 

@test
    void testCategory() throws ServletException, IOException {
        lenient().when(request.getResourceResolver()).thenReturn(resolver);
        request.addRequestParameter("id","id");
        unitTest.doGet(request,response);
        assertEquals(SC_NOT_FOUND,response.getStatus());
        assertEquals("{ \"error\": \"Could not find category for given id.\" }" ,response.getOutputAsString());
    }

 

please give me some idea on how to use session and resource resolver in test cases.

4 Replies

Avatar

Community Advisor

Hi @gargkrishna 

This article explains writing JUNITS for sling model and as well to servlet class refer this to get more information.

https://taylor.callsen.me/unit-testing-aem-sling-models-and-servlets/

Hope it is useful.