Showing posts with label junit. Show all posts
Showing posts with label junit. Show all posts

Friday, June 20, 2014

Data access object unit test using Mokito framework to follow TDD approach

Data access object unit test using Mokito framework to follow TDD approach:

Download MockIto from: 
https://code.google.com/p/mockito/downloads/detail?name=mockito-1.9.5.zip&can=2&q


UserInfoDao .java:

package com.dao;

import java.sql.SQLException;
import com.model.UserModel;

public interface UserInfoDao {
String registerUser(UserModel userInfo) throws SQLException;

}


UserInfoDaoImpl.java:

package com.dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

import com.dao.UserInfoDao;
import com.model.UserModel;

public class UserInfoDaoImpl implements UserInfoDao {

private Connection connection;

public UserInfoDaoImpl(Connection connection) {
super();
this.connection = connection;

}

@Override
public String registerUser(UserModel userInfo) throws SQLException {
System.out.println("dao_registerUser(..) invoked..");
String queryResp = "Failed";
PreparedStatement preStmt = connection
.prepareStatement("insert into user_info(userName,password,firstName,lastName) values (?,?,?,?)");
preStmt.setString(1, userInfo.getUserName());
preStmt.setString(2, userInfo.getPassword());
preStmt.setString(3, userInfo.getFirstName());
preStmt.setString(4, userInfo.getLastName());

if (preStmt.executeUpdate() > 0) {
queryResp = "Success";
}
return queryResp;
}

public Connection getConnection() {
return connection;
}

public void setConnection(Connection connection) {
this.connection = connection;
}
}


UserModel.java:

package com.model;

public class UserModel {
private String userName;
private String password;
private String firstName;
private String lastName;
private int id;

public String getUserName() {
return userName;
}

public void setUserName(String userName) {
this.userName = userName;
}

public String getPassword() {
return password;
}

public void setPassword(String password) {
this.password = password;
}

public String getFirstName() {
return firstName;
}

public void setFirstName(String firstName) {
this.firstName = firstName;
}

public String getLastName() {
return lastName;
}

public void setLastName(String lastName) {
this.lastName = lastName;
}

public int getId() {
return id;
}

public void setId(int id) {
this.id = id;
}

@Override
public String toString() {
return "UserModel [userName=" + userName + ", password=" + password
+ ", firstName=" + firstName + ", lastName=" + lastName
+ ", id=" + id + "]";
}

}


UserInfoService.java:

package com.service;

import com.model.UserModel;

public interface UserInfoService {
String registerUser(UserModel userInfo) throws Exception;
}

UserInfoServiceImpl.java:

package com.service.impl;

import com.dao.UserInfoDao;
import com.model.UserModel;
import com.service.UserInfoService;

public class UserInfoServiceImpl implements UserInfoService {

private UserInfoDao userInfoDao;

public UserInfoServiceImpl(UserInfoDao userInfoDao) {
super();
this.userInfoDao = userInfoDao;
}

@Override
public String registerUser(UserModel userInfo) throws Exception {
System.out.println("service_registerUser(..) invoked..");
return getUserInfoDao().registerUser(userInfo);
}

public UserInfoDao getUserInfoDao() {
return userInfoDao;
}

public void setUserInfoDao(UserInfoDao userInfoDao) {
this.userInfoDao = userInfoDao;
}
}

DaoClient:

package com.client;

import java.sql.Connection;

import com.dao.UserInfoDao;
import com.dao.impl.UserInfoDaoImpl;
import com.model.UserModel;
import com.service.UserInfoService;
import com.service.impl.UserInfoServiceImpl;
import com.util.DBMockUtils;

public class DaoClient {
public static void main(String[] args) throws Exception {
UserModel userInfo = new UserModel();
userInfo.setFirstName("Abhinav");
userInfo.setLastName("Mishra");
userInfo.setPassword("admin");
userInfo.setUserName("admin");
Connection conn = DBMockUtils.getConnection("com.mysql.jdbc.Driver",
"jdbc:mysql://localhost:3306/users", "root", "root");
UserInfoDao dao= new UserInfoDaoImpl(conn);

UserInfoService userServ=new UserInfoServiceImpl(dao);

System.out.println(userServ.registerUser(userInfo));
}
}


UserServiceTest : JUnit Test case.

package com.service.test;

import junit.framework.TestCase;

import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.MockitoAnnotations;

import com.dao.UserInfoDao;
import com.model.UserModel;
import com.service.UserInfoService;
import com.service.impl.UserInfoServiceImpl;

public class UserServiceTest extends TestCase {

private UserInfoService userInfoService;
private UserModel userInfo;

@Mock
private UserInfoDao userInfoDao;

@BeforeClass
public static void oneTimeSetUp() {
// one-time initialization code
System.out.println("@BeforeClass - oneTimeSetUp");
}

@AfterClass
public static void oneTimeTearDown() {
// one-time cleanup code
System.out.println("@AfterClass - oneTimeTearDown");
}

@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
userInfoService = new UserInfoServiceImpl(userInfoDao);
userInfo = new UserModel();
userInfo.setFirstName("Abhinav");
userInfo.setLastName("Mishra");
userInfo.setPassword("admin");
userInfo.setUserName("admin");

System.out.println("@Before - setUp");
}

@After
public void tearDown() {
System.out.println("@After - tearDown");
}

@Test
public void testUserInfoSuccess() throws Exception{
System.out.println("@Test testUserInfoSuccess()...");

Mockito.when(userInfoDao.registerUser(userInfo)).thenReturn("Success");

final String status = userInfoService.registerUser(userInfo);
System.out.println("Expected Result: " + status);

// Verify state
assertEquals("Success", status);

// Verify that method invoked actually or not
Mockito.verify(userInfoDao).registerUser(userInfo);

// verify the object with no. of times invocation
Mockito.verify(userInfoDao, Mockito.timeout(1)).registerUser(userInfo);
}

@Test
public void testUserInfoFailure() throws Exception {
System.out.println("@Test testUserInfoFailure()...");

Mockito.when(userInfoDao.registerUser(userInfo)).thenReturn("Failed");

final String status = userInfoService.registerUser(userInfo);
System.out.println("Expected Result: " + status);

// Verify state
assertEquals("Failed", status);

// Verify that method invoked actually or not
Mockito.verify(userInfoDao).registerUser(userInfo);

// verify the object with no. of times invocation
Mockito.verify(userInfoDao, Mockito.timeout(1)).registerUser(userInfo);

}
}


Output:


@Before - setUp

@Test testUserInfoSuccess()...

service_registerUser(..) invoked..

Expected Result: Success

@After - tearDown

@Before - setUp

@Test testUserInfoFailure()...

service_registerUser(..) invoked..

Expected Result: Failed

@After - tearDown





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...