mardi 17 septembre 2019

How to write tests for HttpServlet with 100% coverage?

I'm trying to implement tests to my project where i mostly use HttpServlet. I need to write some tests for all gets and posts.

I have tried searching for how to write the tests with mockito and similar libraries, but I just got nullpointer errors.

This is the function I want to test.

package Handlers;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebServlet("/")
public class Index extends HttpServlet {
    public Index() {

    }

    @Override
    public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("text/html");
        resp.setCharacterEncoding("UTF-8");
        resp.getWriter().write("<h1>Welcome to my index page</h1><h2>This is all</h2>");
        resp.setStatus(HttpServletResponse.SC_ACCEPTED);
    }
}

With the following test code I could get the test to pass and get 100% test coverage, but it's just hardcoded really.

    @Test
    public void TestDoGet() throws ServletException, IOException {

        HttpServletResponse response = mock(HttpServletResponse.class);
        HttpServletRequest request = mock(HttpServletRequest.class);

        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw);

        when(response.getWriter()).thenReturn(pw);
        when(response.getStatus()).thenReturn(202); // Hardcode

        Index index = new Index();
        index.doGet(request, response);

        assertEquals(202, response.getStatus());

    }

I did try to just use Unirest.Get() on the function, which worked, but then I got 0% test coverage.

Aucun commentaire:

Enregistrer un commentaire