Java – Dbunit does not clean up and insert the database after each method, so the test is not independent
I have a Dao class test. I use Dbunit to create and populate the database (using Derby in memory)
This is the code (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 a test (disabled to avoid side 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()); }
Solution
This is because clean_ Insert "cleans" before testing, not after testing
For example, if there are two tests, test1 and test2 Test1 and test2 are from test1 XML and test2 XML populates the table
test1. XML is like
<dataset> <table1 ... /> <table2 ... /> </dataset>
test2. XML is good
<dataset> <table1 ... /> </dataset>
When the test order is test1 and then test2, clear_ Insert will do the following:
>Delete everything from table2 > delete everything from table1 > delete test1 Insert data from XML into table1 > test1 Insert data in XML into table2 > execute test1 > delete all contents from table1 > put test2 Insert data in XML into table1 > execute test2
Therefore, when test2 is executed, table1 contains data from test2 XML data, which is exactly what we expect However, table2 still contains test1 data, which may cause some problems
The solution is to create an empty row for each table in all XML files It will ensure that all tables are cleared before insertion
For the above example,
test1. XML would be like this
<dataset> <table1 ... /> <table2 ... /> <table1 /> <table2 /> </dataset>
test2. XML is good
<dataset> <table1 ... /> <table1 /> <table2 /> </dataset>