DbUnit

DbUnit erweitert JUnit um die Fähigkeit, mit relationalen Datenbanken zu testen. Eine Hauptaufgaben von DbUnit ist das Sicherstellen von bekannten und konsistenten Datenbankzuständen vor und zwischen den Tests.

Voraussetzungen sind folgende Bibliotheken:

Die zu testende Klasse: class LoadPersons


package de.snowbits.db;

import static de.snowbits.tools.SQLTools.close;
import static de.snowbits.tools.SQLTools.getInteger;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

import de.snowbits.pojo.Person;
import de.snowbits.pojo.Sex;
import de.snowbits.tools.GenericDBLoader;

public class LoadPersons {
	
	private static final String SQL_PERSON = "SELECT id, age, sex, firstname, lastname FROM person";

	private Connection _connection;

	public List<Person> load(Connection connection) throws Exception {
		try {
			_connection = connection;
			
			return load();
		} catch (SQLException e) {
			throw e;
		} catch (Exception e) {
			close(_connection);
			throw new Exception("Error at loading all persons.", e);
		}
	}

	public List<Person> loadBetweenAge(Integer fromAge, Integer toAge, Connection connection) throws Exception {
		try {
			_connection = connection;
			
			return loadBetweenAge(fromAge, toAge);
		} catch (SQLException e) {
			throw e;
		} catch (Exception e) {
			close(_connection);
			throw new Exception("Error at loading persons between: fromAge=" + fromAge + " and toAge=" + toAge, e);
		}
	}	
	
	private List<Person> load() throws SQLException {
		return new GenericDBLoader<Person>(SQL_PERSON) {

			@Override
			protected Connection getConnection() throws SQLException {
				return _connection;
			}

			@Override
			protected Person resolve(ResultSet rs) throws SQLException {
				return getPerson(rs);
			}

		}.getAll();
	}
	
	private List<Person> loadBetweenAge(Integer fromAge, Integer toAge) throws SQLException {
		PreparedStatement stmt = _connection.prepareStatement(SQL_PERSON + " WHERE age BETWEEN ? AND ?");
		
		int index = 1;
		stmt.setInt(index++, fromAge);
		stmt.setInt(index++, toAge);
		
		return new GenericDBLoader<Person>(null) {

			@Override
			protected Connection getConnection() throws SQLException {
				return _connection;
			}

			@Override
			protected Person resolve(ResultSet rs) throws SQLException {
				return getPerson(rs);
			}
			
		}.getAll(stmt);
	}	
	
	private Person getPerson(ResultSet rs) throws SQLException {
		Person result = new Person(getInteger(rs, "id"));
		result.setAge(getInteger(rs, "age"));
		result.setSex(Sex.getValue(rs.getString("sex")));
		result.setFirstname(rs.getString("firstname"));
		result.setLastname(rs.getString("lastname"));
		return result;
	}
	
}
	

Abhängigkeiten siehe:


Der Test der Klasse LoadPersons: class LoadPersonsTest


package de.snowbits.db;

import static de.snowbits.tools.SQLTools.close;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;

import java.sql.Connection;
import java.util.List;

import org.junit.Test;

import de.snowbits.AbstractDBTestBase;
import de.snowbits.SQLTableProvider.Tables;
import de.snowbits.pojo.Person;

public class LoadPersonsTest extends AbstractDBTestBase {

	private List<Person> _loaded;

	@Override
	protected void setUpBefore() throws Exception {
		_loaded = null;
	}
	
	@Test
	public void loadAllPersons() throws Exception {
		loadAll();
		assertNotNull(_loaded);
		assertTrue("Personenanzahl stimmt nicht", _loaded.size() == 6);
	}

	@Test
	public void loadBetweenAge20and30() throws Exception {
		loadBetween(20, 30);
		assertNotNull(_loaded);
		assertTrue("Personenanzahl stimmt nicht", _loaded.size() == 2);
	}

	private void loadAll() throws Exception  {
		Connection connection = null;
		try {
			connection = getConnection();
			_loaded = testee().load(connection);
		} catch (Exception e) {
			close(connection);
			throw e;
		}
	}
	
	private void loadBetween(int fromAge, int toAge) throws Exception {
		Connection connection = null;
		try {
			connection = getConnection();
			_loaded = testee().loadBetweenAge(fromAge, toAge, connection);
		} catch (Exception e) {
			close(connection);
			throw e;
		}		
	}

	@Override
	protected Tables[] installTables() {
		return new Tables[] { Tables.person };
	}

	@Override
	protected DatasetOwner getDatasetOwner() {
		return new DatasetOwner(this.getClass(), "LoadPersons.xml");
	}

	private LoadPersons testee() {
		return new LoadPersons();
	}
}
	

XML LoadPersons.xml


<?xml version="1.0" encoding="UTF-8"?>
<dataset>
	<person id="1" sex="M" age="25" firstname="Max" lastname="Muster" />
	<person id="2" sex="F" age="22" firstname="Maxi" lastname="Muster" />
	<person id="3" sex="M" age="8" firstname="Mäxchen" lastname="Muster" />
	<person id="4" sex="F" age="12" firstname="Maxiline" lastname="Muster" />
	<person id="5" sex="M" age="65" firstname="Maximo" lastname="Muster" />
	<person id="6" sex="F" age="58" firstname="Maxima" lastname="Muster" />
</dataset>
	

class AbstractDBTestBase


package de.snowbits;

import static de.snowbits.tools.SQLTools.close;

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

import org.dbunit.IDatabaseTester;
import org.dbunit.JdbcDatabaseTester;
import org.dbunit.dataset.DataSetException;
import org.dbunit.dataset.IDataSet;
import org.dbunit.dataset.xml.FlatXmlDataSetBuilder;
import org.junit.After;
import org.junit.Before;

import de.snowbits.SQLTableProvider.Tables;

public abstract class AbstractDBTestBase {
	
	private IDatabaseTester _dbTester;
	private SQLTableProvider _tableProvider = new SQLTableProvider(); 
	
	@Before
	public void setUp() throws Exception {
		_dbTester = new JdbcDatabaseTester("org.hsqldb.jdbcDriver",
						   "jdbc:hsqldb:mem:PUBLIC", "sa", "");
		createTables(installTables());
		_dbTester.setDataSet(getDataset());
		_dbTester.onSetup();		
		setUpBefore();
	}

	@After
	public void tearDown() throws Exception {
		_dbTester.onTearDown();
	}
	
	protected abstract void setUpBefore() throws Exception;
	protected abstract Tables[] installTables();
	protected abstract DatasetOwner getDatasetOwner();
	
	protected Connection getConnection() throws Exception {
		return _dbTester.getConnection().getConnection();
	}
		
	private void createTables(Tables[] tables) throws Exception {
		Connection conn = null;
		Statement stmt = null;
		try {
			conn = getConnection();
			stmt = conn.createStatement();
		 
			 for (Tables element : tables) {
				 stmt.execute(_tableProvider.getDrop(element));
				 stmt.execute(_tableProvider.getCreate(element));
			 }
			 
			 close(stmt, conn);
		} catch (Exception e) {
			close(stmt, conn);
			throw e;
		}
	}

	private IDataSet getDataset() throws DataSetException {
		FlatXmlDataSetBuilder builder = new FlatXmlDataSetBuilder();
		String dataFile = getDatasetOwner().getClassName()
	                     .substring(0, getDatasetOwner().getClassName().lastIndexOf(".")).replace(".", "/") 
	                     + "/" + getDatasetOwner().getDatasetName();
		
		return builder.build(getClass().getClassLoader().getResourceAsStream(dataFile));
	}
	
	protected final class DatasetOwner {
		private String _className;
		private String _datasetName;
		
		public DatasetOwner(Class<?> clazz, String datasetFilename) {
			_className = clazz.getName();
			_datasetName = datasetFilename;
		}

		public String  getClassName() {
			return _className;
		}
		
		public String getDatasetName() {
			return _datasetName;
		}
		
	}
		
}
	

class SQLTableProvider


package de.snowbits;

import java.util.Hashtable;

public class SQLTableProvider {

	public enum Tables {
		person;
	}
	
	private Hashtable&tl;Tables, String> _cache = new Hashtable<>();
	
	public SQLTableProvider() {
		// TODO: reading source file
		_cache.put(Tables.person, "CREATE TABLE " + Tables.person + " ( "
				+ " id INTEGER UNIQUE,"
				+ " sex VARCHAR(1),"
				+ " firstname VARCHAR(100),"
				+ "	lastname VARCHAR(100),"
				+ "	age INTEGER)");
	}
	
	public String getDrop(Tables table) {
		return "DROP TABLE " + table + " IF EXISTS";
	}
	
	public String getCreate(Tables table) {
		return _cache.get(table);
	}
	
}
	

Top


Example
Sitemap Kontakt Impressum