DBUnit Sample Program

DbUnit is an open source Framework created by Manuel Laflamme. DBUnit is a powerful tool for simplifying Unit Testing of the database operations. It extends the popular JUnit test framework. DbUnit provides a very simple XML based mechanism for loading the test data, in the form of data set in XML file, before a test runs. Moreover the database can be placed back into its pre-test state at the completion of the test.
DBUnit training provides all the theoretical concepts and practical knowledge ranging from introduction and setting up the environment to writing and running tests with suitable examples. After completing this course you will be able to do Unit Testing of the database operations safely and avoid problems that can occur when one test corrupts the database and causes subsequent test to fail.
This helps the developers to quickly Unit test database driven applications. You can completely test persistence layer of your application.


DBUnit Testing Sample Programs

This is my class, now we are going to write test class using DBUnit. As per above information DBUnit purpose is to write test case for DB connected classes alone. Here will provide dummy data for DB and will execute the test cases using that data.
package org.JavaVillage.com;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

/** * @author Munna * Salary Calculation */
public class SalaryCalcutation {
	/** * Creating Connection * @return Connection * @throws SQLException */
	private Connection getConnection() throws SQLException {
		return DriverManager.getConnection(
				"jdbc:mysql://localhost:3306/Company", "root", "");
	}

	/**
	 * * Salary Calculation * @param EmpID string * @return salary * @throws
	 * SQLException
	 */
	public int calculator(String EmpID) throws SQLException {
		Statement stmt = getConnection().createStatement();
		ResultSet rs = stmt
				.executeQuery("select * from salarydetails where EmpID='"
						+ EmpID + "'");
		int salary = 0;
		int bonus = 0;
		int increment = 0;
		while (rs.next()) {
			salary = rs.getInt("Salary");
			bonus = rs.getInt("Bonus");
			increment = rs.getInt("Increment");
		}
		return (salary + bonus + increment);
	}
}
Explanation about the class: Main aim of the class is for calculating salaries for the employees. As of now I have written two methods, one is database connectivity other one is for calculating salary for specific member based on employee id.
Now we are going to write test class for above class...
And one more thing we have to provide DataSet for DBUnit Test case. This is our xml for dataset with salarydetails table with column values.
dbunitData.xml:
<?xml version='1.0' encoding='UTF-8'?>
	<dataset>      
		<!--Salary Table -->
		<salarydetails EmpID="24356A" Salary="10000" Bonus="0" Increment="3245" />
	</dataset>


DBUnit test class (SalaryCalculationTest_DB.java):
package org.JavaVillage.com;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
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 org.junit.Test;

/** * * @author Munna * Test class for SalaryCalcutation using DBUNIT * */
public class SalaryCalculationTest_DB extends DatabaseTestCase {
	public static final String TABLE_LOGIN = "salarydetails";
	private FlatXmlDataSet loadedDataSet;
	private SalaryCalcutation salaryCalicutation;
	private Connection jdbcConnection;

	/** * Provide a connection to the database * @return IDatabaseConnection */
	protected IDatabaseConnection getConnection() throws Exception {
		Class.forName("com.mysql.jdbc.Driver");
		jdbcConnection = DriverManager.getConnection(
				"jdbc:mysql://localhost:3306/Company", "root", "");
		return new DatabaseConnection(jdbcConnection);
	}

	/** * Load the data which will be inserted for the test * @return IDataSet */
	protected IDataSet getDataSet() throws Exception {
		loadedDataSet = new FlatXmlDataSet(this.getClass().getClassLoader()
				.getResourceAsStream("dbunitData.xml"));
		return loadedDataSet;
	}

	/** * Test case for calculator * positive scenario---Valid Employee */
	@Test
	public void testCalculator() throws SQLException {
		salaryCalicutation = new SalaryCalcutation();
		int salary = salaryCalicutation.calculator("24356A");
		assertEquals(13245, salary);
	}

	/** *Test case for calculator *negative scenario---InValid Employee */
	@Test
	public void testCalculatorNeg() throws SQLException {
		salaryCalicutation = new SalaryCalcutation();
		int salary = salaryCalicutation.calculator("24356B");
		assertEquals(0, salary);
	}
}
Explanation about DBUnit class: Here also we have database connectivity but data is whatever we have provided in xml will be considering as rows in DB. Instead of using actual data we are providing dummy data for DBUnit, especially for test method for database connectivity classes.
Provided methods in test class:
  • getConnection: Database connection
  • getDataSet: dataset
  • testCalculator: actual test class for calculator method in positive scenario means employee is valid.
  • testCalculatorNeg: negative scenario for calculator method in negative scenario means employee is invalid.



Here 1 and 2 methods are implementations for super class and 3 and 4 are test cases for calculator method.
Required Database Changes: In database, whatever details we have provided for database connectivity it should be proper in database like DB name and table name. Coming to the data will be taken from dataset from xml(dbunitData.xml).
To download sql file for DB changes click on sql file

SQL icon to download DB changes for DBUNIT sample program


See the structure of project and also required jars for the DBUNIT:

DBUnit structure for sample project with required jars

Execution

DBUnit execution