Tuesday, June 05, 2018

How to do JUnit for Servlet class

Mockito class can be used to do JUnit for your servlet
Lets say we have following below given servlet in our code
package com.siddhu;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class HelloWorldServlet extends HttpServlet {
private static final long serialVersionUID = 1031422249396784970L;
public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
resp.setContentType("text/html");
PrintWriter out = resp.getWriter();
out.print("Hello World from Servlet");
out.flush();
out.close();
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
doGet(request, response);
} catch (ServletException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// TODO Auto-generated method stub
}
}
And we want to do Junit for this servlet follow below given steps
1- If you project is MAVEN add follwing line in your POM.xml
org.mockito
mockito-all
1.9.5
test
junit
junit
4.12
test
2- If your project is normale dynamic project please add above jar to your project build path
3- Create a new class in the same package for doing JUnit
package com.siddhu;
import static org.junit.Assert.assertTrue;
import static org.mockito.Mockito.*;
import java.io.PrintWriter;
import java.io.StringWriter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.junit.Test;
import org.mockito.Mockito;
public class TestHelloWorldServlet extends Mockito{
@Test
public void testServlet() throws Exception {
HttpServletRequest request = mock(HttpServletRequest.class);
HttpServletResponse response = mock(HttpServletResponse.class);
//Way to set parameter in servlet
/*when(request.getParameter("username")).thenReturn("me");
when(request.getParameter("password")).thenReturn("secret");*/
StringWriter stringWriter = new StringWriter();
PrintWriter writer = new PrintWriter(stringWriter);
when(response.getWriter()).thenReturn(writer);
new HelloWorldServlet().doPost(request, response);
//verify(request, atLeast(1)).getParameter("username"); // Checking the value if username as same from calling servlets
writer.flush(); // it may not have been flushed yet...
assertTrue(stringWriter.toString().contains("Hello World from Servlet"));
}
}
3- If you are using Eclipse run the above class as right click --> run as --> Junit Test and you will find below screen
Image1