DbUnit @DatabaseTearDown annotation: how to delete only certain records? (those inserted using @DatabaseSetup annotation)

10.6k views Asked by At

I am trying to delete only those records I inserted using the @DatabaseSetup annotation.

My test looks like this:

@Test
@DatabaseSetup("classpath:data-set.xml")
@DatabaseTearDown(value={"classpath:data-set.xml"}, type= DatabaseOperation.DELETE)
public void testSomething() throws Exception {

data-set.xml

<?xml version="1.0" encoding="UTF-8"?>
<dataset>
    <person id="1" name="Joe"/>
</dataset>

Supposedly, using DatabaseOperation.DELETE means "Deletes database table rows that matches rows from the dataset." But when I execute the test it erases all data in my table.

I think the problem is the format of the xml file used for tear-down. I tried using different formats:

first try at tear-down.xml

<?xml version="1.0" encoding="UTF-8"?>
<dataset>
    <person id="1"/>
</dataset>

second try at tear-down.xml

<?xml version="1.0" encoding="UTF-8"?>
<dataset>
    <person/>
</dataset>

And regardless of the format used, it always deletes all data in the table. I can't find a single exmaple of the format used for tear-down that doesn't simply list the table name. In most examples, people seem to use the same xml file both for setup and tear-down.

But this has to be possible, no?

1

There are 1 answers

1
Markus Schmalhofer On

The records inserted into the database are not deleted by the @DatabaseTearDown annotation, but by @DatabaseSetup. The reason is that DbUnit, by default, cleans the tables and after that inserts the test records. You can prevent this by using DatabaseOperation.INSERT.