Skip to content

Instantly share code, notes, and snippets.

@irof
Created March 7, 2013 23:39
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save irof/5112912 to your computer and use it in GitHub Desktop.
Save irof/5112912 to your computer and use it in GitHub Desktop.
#junitbook P.203 のをJdbcDatabaseTesterで書いてみたもの
package net.hogedriven.irof.sandbox;
import org.dbunit.JdbcDatabaseTester;
import org.dbunit.database.DatabaseConfig;
import org.dbunit.database.IDatabaseConnection;
import org.dbunit.dataset.IDataSet;
import org.dbunit.ext.h2.H2DataTypeFactory;
import org.junit.rules.TestRule;
import org.junit.runner.Description;
import org.junit.runners.model.Statement;
import java.sql.Connection;
public abstract class DbUnitTester extends JdbcDatabaseTester implements TestRule {
public DbUnitTester(String driverClass, String connectionUrl, String username, String password, String schema) throws ClassNotFoundException {
super(driverClass, connectionUrl, username, password, schema);
}
@Override
public IDatabaseConnection getConnection() throws Exception {
IDatabaseConnection connection = super.getConnection();
DatabaseConfig config = connection.getConfig();
config.setProperty(DatabaseConfig.PROPERTY_DATATYPE_FACTORY, new H2DataTypeFactory());
return connection;
}
protected void executeQuery(String sql) throws Exception {
Connection conn = getConnection().getConnection();
conn.createStatement().execute(sql);
conn.commit();
conn.close();
}
protected void before() throws Exception {
}
protected void after() throws Exception {
}
abstract protected IDataSet createDataSet() throws Exception;
@Override
public Statement apply(final Statement base, Description description) {
return new Statement() {
@Override
public void evaluate() throws Throwable {
before();
setDataSet(createDataSet());
onSetup();
try {
base.evaluate();
} finally {
try {
after();
} finally {
onTearDown();
}
}
}
};
}
}
package net.hogedriven.irof.sandbox;
import org.dbunit.dataset.xml.FlatXmlDataSetBuilder;
import org.junit.ClassRule;
import org.junit.Rule;
import org.junit.Test;
public class HogeTest {
@ClassRule
public static H2DatabaseServer s = new H2DatabaseServer("h2", "db", "ut");
@Rule
public DbUnitTester tester() throws ClassNotFoundException {
return new DbUnitTester("org.h2.Driver", "jdbc:h2:tcp://localhost/db;SCHEMA=ut", "sa", "", "ut") {
@Override
protected void before() throws Exception {
executeQuery("DROP TABLE IF EXISTS users");
executeQuery("CREATE TABLE users(id INT AUTO_INCREMENT, name VARCHAR(255))");
}
@Override
protected org.dbunit.dataset.IDataSet createDataSet() throws Exception {
return new FlatXmlDataSetBuilder().build(getClass().getResourceAsStream("/fixtures.xml"));
}
};
}
// Tests...
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment