I have a test for a DAO class, I use DBUnit to create and populate the database (using an in-memory derby). I am in problems when testing the dao update method because it modify the data and then the other test fails. As all of us know a test should be independent of any other, and I know that DBUnit has some facilities to clean and regenerate the database after every test. But it does not work!
The code is this (TestNG):
@BeforeMethod
public void prepareData() throws Exception {
cleanAndPopulate("users");
}
public void cleanAndPopulate (String nameXML) throws Exception {
IDatabaseConnection conn;
conn = new DatabaseConnection (sessionForTesting.connection());
InputStream is = DBconnection.class.getClassLoader()
.getResourceAsStream(nameXML + ".xml");
dataset = new FlatXmlDataSet(is);
System.out.println("*** Preparando base de datos de test");
DatabaseOperation.CLEAN_INSERT.execute(conn, dataset);
}
This is the test (disabled to avoid collateral effects):
@Test(enabled=false) // Deja la BBDD en estado erroneo!!!
public void busco_y_actualizo() throws Exception {
PacoUser resultado = userdao.getById(1L);
resultado.setName("OTRO");
userdao.update(resultado);
PacoUser resultado2 = userdao.getById(1L);
AssertJUnit.assertNotNull(resultado2);
AssertJUnit.assertEquals("OTRO", resultado2.getName());
}