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

1

5

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?

Croatia answered 9/12, 2014 at 10:44 Comment(0)
T
7

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.

Tedra answered 9/12, 2014 at 14:25 Comment(1)
Wow! That was it! I was just about to write back saying that that is not what was happening to me, that the rest of my tables are not having their data erased. Which is true. But I guess what DBUnit does by default is a CLEAN_INSERT for the tables in your data-set.xml. But before opening my big mouth I tried your suggestion and changed @DatabaseSetup to use INSERT and now DBUnit is only erasing the data in my tables that was inserted by DBUnit itself. Many thanks!Croatia

© 2022 - 2024 — McMap. All rights reserved.