Friday, June 20, 2014

Testing servlets using JUNIT and MockIto

Testing Servlets using JUNIT and Mockito:


Mockito framework:



I have used version 1.10.19 of mockito-all for this post.

<!-- https://mvnrepository.com/artifact/org.mockito/mockito-all -->
<dependency>
    <groupId>org.mockito</groupId>
    <artifactId>mockito-all</artifactId>
    <version>1.10.19</version>
    <scope>test</scope>
</dependency>

Limitations:

1- Final,anonymous and primitive types can not be mocked.
2- Methods with return type "void"called from within doPost or doGet methods can not be mocked.

Servlet:

package com.github.abhinavmishra14.demo.servlet;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * The Class Login.
 */
public class Login extends HttpServlet {
	
	/** The Constant serialVersionUID. */
	private static final long serialVersionUID = 38044879686270933L;

	/**
	 * Instantiates a new login.
	 */
	public Login() {
		super();
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see javax.servlet.GenericServlet#init(javax.servlet.ServletConfig)
	 */
	@Override
	public void init(ServletConfig config) throws ServletException// called once servlet loads
	{
		System.out.println("Login Init called...");
		try {
			super.init(config);
		} catch (ServletException e) {
			e.printStackTrace();
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see javax.servlet.GenericServlet#destroy()
	 */
	@Override
	public void destroy()// called just before servlet unload
	{
		System.out.println("Login Destroyed...");
		super.destroy();
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * javax.servlet.http.HttpServlet#doPost(javax.servlet.http.HttpServletRequest,
	 * javax.servlet.http.HttpServletResponse)
	 */
	@Override
	public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
		System.out.println("Login doPost...");
		String name = req.getParameter("user");
		String pwd = req.getParameter("password");
		String rememberMe = req.getParameter("rememberMe");
		System.out.println("User: " + name + " | password: " + pwd);
		if (name.equals("abhinav") && pwd.equals("passw0rd")) {
			HttpSession session = req.getSession();
			session.setAttribute("user", name);
			Cookie ck1 = new Cookie("user", name);
			Cookie ck2 = new Cookie("pwd", pwd);
			res.addCookie(ck1);
			res.addCookie(ck2);
			if (rememberMe != null && rememberMe != "") {
				Cookie ck3 = new Cookie("rememberMe", rememberMe);
				res.addCookie(ck3);
			}
		}

		PrintWriter out = res.getWriter();
		out.write("Login successfull...");
		// Dispatching request
		RequestDispatcher rd = req.getRequestDispatcher("/HelloWorld.do");
		rd.forward(req, res);
	}
}



TestCase:

package com.github.abhinavmishra14.demo.servlet.test;

import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

import java.io.PrintWriter;
import java.io.StringWriter;

import javax.servlet.RequestDispatcher;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import junit.framework.TestCase;

import org.junit.Before;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;

import com.github.abhinavmishra14.demo.servlet.Login;

public class LoginServletTest extends TestCase {

	@Mock
	HttpServletRequest request;
	@Mock
	HttpServletResponse response;
	@Mock
	HttpSession session;

	@Mock
	RequestDispatcher rd;

	@Before
	protected void setUp() throws Exception {
		MockitoAnnotations.initMocks(this);
	}

	@Test
	public void test() throws Exception {
		when(request.getParameter("user")).thenReturn("abhinav");
		when(request.getParameter("password")).thenReturn("passw0rd");
		when(request.getParameter("rememberMe")).thenReturn("Y");
		when(request.getSession()).thenReturn(session);
		when(request.getRequestDispatcher("/HelloWorld.do")).thenReturn(rd);

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

		when(response.getWriter()).thenReturn(pw);

		new Login().doPost(request, response);

		// Verify the session attribute value
		verify(session).setAttribute("user", "abhinav");

		verify(rd).forward(request, response);

		String result = sw.getBuffer().toString().trim();

		System.out.println("Result: " + result);

		assertEquals("Login successfull...", result);
	}
}


Output:

Login doPost...
User: abhinav | password: passw0rd
Result: Login successfull...



No comments:

Post a Comment

Thanks for your comments/Suggestions.