Example Implementing Unit Test Case using JUnit and DBUnit

Example Implementing Unit Test Case using JUnit and DBUnit

Scenario:

Consider we need to write a method in DAL class that would check if the user is login by looking a flag in DB against userid and password. Following is the user database table that this method would access:

User Table

Fields Description
id Primary key
Userid User unique id to login
Password User password for login
First Name User firstname
Last Name User LastName
Email User email address
IsUserLogin Bit Flag having value 0 or 1 if user is login

Implementing the scenario using TDD approach

Step 1- creating test first:

Since TDD follows write test first approach so we would first write our test case and then the actual code. We would first write UserDALTest class as follows with the method called testIsUserLogin():

package com.dal;

import junit.framework.TestCase;

public class UserDALTest extends TestCase {

public void testIsUserLogin(){

}

}

Step 2-Adding test code :

We would add test code in the method as follows:

package com.dal;

import junit.framework.TestCase;

public class UserDALTest extends TestCase {

public void testIsUserLogin(){

UserDAL userDal=new UserDAL();

boolean isUserLogin=userDal.isUserLogin(“imamraza”);

assertTrue(“The user should be Login”,isUserLogin);

}

}

The test would not compile as we have not created UserDAL class and its method yet. Most of the editors provides feature to generate the unimplemented class from the test case. I am using Eclipse so I would just right click on it and generate basic skeleton of the class. The generated UserDAL class is as follows:

package com.dal;

public class UserDAL {

public boolean isUserLogin(String username) {

// TODO Auto-generated method stub

return false;

}

}

As you saw that it do nothing only return false. Our test case is making sure that the isUserLogin should be true while our generated class is returning false. This should make our test fail. We would run it and see that the test fail with following message:

junit.framework.AssertionFailedError: The user should be Login

at junit.framework.Assert.fail(Assert.java:47)

at junit.framework.Assert.assertTrue(Assert.java:20)

at com.dal.UserDALTest.testIsUserLogin(UserDALTest.java:8)

So this is what is expected.

Step 3- Adding setup data:

For real testing we need to first populate our database with setup data having username=imamraza that we used in our test case above. Here comes the role of DBUnit. We would modify our test case to extend from DBUnit framework as follows:

package com.dal;

import java.io.FileInputStream;

import java.sql.DriverManager;

import org.dbunit.DatabaseTestCase;

import org.dbunit.database.DatabaseConnection;

import org.dbunit.database.IDatabaseConnection;

import org.dbunit.dataset.IDataSet;

import org.dbunit.dataset.xml.FlatXmlDataSet;

import junit.framework.TestCase;

public class UserDALTest extends TestCase {

public void testIsUserLogin(){

insertFileIntoDb(“c:\\user.xml”);

UserDAL userDal=new UserDAL();

boolean isUserLogin=userDal.isUserLogin(“imamraza”,“chacha”);

assertTrue(“The user is not Login”,isUserLogin);

}

protected void insertFileIntoDb(String fileName) throws Exception

{

DatabaseOperation.CLEAN_INSERT.execute(getConnection(),new FlatXmlDataSet(new FileInputStream(fileName)));

}

private IDatabaseConnection getConnection() throws Exception {

try{

Class driverClass =

Class.forName(“org.gjt.mm.mysql.Driver”);

}catch(ClassNotFoundException cnfe)

{

cnfe.printStackTrace();

}

return new DatabaseConnection( DriverManager.getConnection(

“jdbc:mysql://localhost:3307/test”, “root”

, “root”));

}

}

Following changes has been made in this test case:

  • We import DBUnit classes.

  • Write two methods :

  • insertFileIntoDb() -This method insert our setup data into the DB using DBUnits.

  • getConnection()– This method returns Database connection or our test DB.

User XML file Content

Followings are content of User.xml file that we used in Dbunit to populate our database with.

<?xml version=’1.0′ encoding=’UTF-8′?>

<dataset>

<User userid=’imamraza’ password=’chacha’ isUserLogin=’1’/>

</dataset>

Step 4- Writing Code to pass test:

Now we would write code in UserDAL to pass our test. Below is the updated code for UserDAL class:

package com.dal;

import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.ResultSet;

import java.sql.SQLException;

import org.dbunit.database.DatabaseConnection;

public class UserDAL {

public boolean isUserLogin(String username) throws SQLException {

// TODO Auto-generated method stub

ResultSet rs= getConnection().createStatement()

.executeQuery(“select isUserLogin from User where userid='”+username+“‘”);

if(rs.next())

return rs.getBoolean(1);

else

return false;

}

private Connection getConnection() throws SQLException{

try{

Class driverClass =

Class.forName(“org.gjt.mm.mysql.Driver”);

}catch(ClassNotFoundException cnfe)

{

cnfe.printStackTrace();

}

return DriverManager.getConnection(

“jdbc:mysql://localhost:3307/test”, “root”

, “root”);

}

}

Step 5- Adding scenario to test case:

Currently we are testing only one scenario in which user is login. Now we would another scenario in which user would not login in that case our UserDAL method should return false. To add scenario in the test case we used DBUnit feature called replacementDataSet. This feature provide you facility to change tag defined in setup db xml at runtime. Now we will change our user.xml to include tag as shown below:

<?xml version=’1.0′ encoding=’UTF-8′?>

<dataset>

<User userid=’imamraza’ password=’chacha’ isUserLogin=’[isUserLogin]‘/>

</dataset>

You will notice that there is tag added with the name “[isUserLogin]” in the XML,so that we can change to false or true thus making testing scenario. How will do that in test case, see below test class code:

public void testIsUserLogin()throws Exception{

ReplacementDataSet replacementDataSet = getReplacementDataSet(“c:\\user.xml”);

replacementDataSet.addReplacementObject(“[isUserLogin]”, “1”);

insertDataSetIntoDb(replacementDataSet);

UserDAL userDal=new UserDAL();

boolean isUserLogin=userDal.isUserLogin(“imamraza”);

assertTrue(“The user should be Login”,isUserLogin);

replacementDataSet = getReplacementDataSet(“c:\\user.xml”);

replacementDataSet.addReplacementObject(“[isUserLogin]”, “0”);

insertDataSetIntoDb(replacementDataSet);

userDal=new UserDAL();

isUserLogin=userDal.isUserLogin(“imamraza”);

assertFalse(“The user should not be Login”,isUserLogin);

}

public ReplacementDataSet getReplacementDataSet(String fileName) throws DataSetException, FileNotFoundException, IOException

{

return new ReplacementDataSet(getFlatXmlDataSet(fileName));

}

private FlatXmlDataSet getFlatXmlDataSet(String fileName) throws DataSetException, FileNotFoundException, IOException

{

return new FlatXmlDataSet(new FileInputStream(fileName));

}

Advertisements

3 thoughts on “Example Implementing Unit Test Case using JUnit and DBUnit

  1. assalaam alikum
    “this example is very nise i want more example on test cases please if u dont mind please send me more mexamples on test caases”
    mashalaha ye example bahot pasnd aya
    mujhe istarthe ke abihe examples testcases per bhejiye
    alha hafiz

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s