I used the same database engine that main database and dbunit for cleaning up before each test.
public class SomeTest {
// ...
@Before
public void startApp() throws Exception {
// Set up connection to test database, different from main database. Config better should be used instead of hard-coding.
Map<String, String> settings = new HashMap<String, String>();
settings.put("db.default.url", "jdbc:mysql://localhost/somedatabase?characterEncoding=UTF-8&useOldAliasMetadataBehavior=true");
settings.put("db.default.user", "root");
settings.put("db.default.password", "root");
settings.put("db.default.jndiName", "DefaultDS"); // make connection available to dbunit through JNDI
app = Helpers.fakeApplication(settings);
Helpers.start(app);
databaseTester = new JndiDatabaseTester("DefaultDS");
IDataSet initialDataSet = new FlatXmlDataSetBuilder().build(play.Play.application()
.resourceAsStream("/resources/dataset.xml"));
databaseTester.setDataSet(initialDataSet);
databaseTester.onSetup();
}
@After
public void stopApp() throws Exception {
databaseTester.onTearDown();
Helpers.stop(app);
}
}
My dataset.xml
just contain table names to tell dbunit to empty these tables before each test. It also can contain fixtures.
<?xml version="1.0" encoding="UTF-8"?>
<dataset>
<name_of_my_first_table />
<name_of_my_second_table />
</dataset>
Evolutions run automatically on test database when using this approach, so if you remove all tables from test database, they will be recreated.
It is overkill to use dbunit if you only need to clean tables, you can clean them by issuing query directly or by using ebean DdlGenerator
. But I also use dbunit for comparing data.
I don't use Helpers.running
, because it takes Runnable
and Runnable
implementations cannot throw exceptions - very inconvenient for tests. But if you look at code for running()
, it just calls Helpers.start()
and Helpers.stop()
so I call these methods directly in @Before
and @After
.
Decided not to use H2 for running tests: yes, it runs faster, but there are too much difference between it and MySQL.