Search code examples
javaspring-bootspring-testdbunitspring-test-dbunit

How to prevent data deletion when using DBUnit


I use Spring Boot with liquibase.

The problem is that when there is already data in a specific table in the database and I try to add more data to this table in DBUnit tests, then DBUnit deletes all the data and inserts only its own data.

I will give an example, I have already inserted five authors in the database. Test without DBUnit:

@RunWith(SpringRunner.class)
@SpringBootTest
public class AuthorsManagerTest {

    @Autowired
    private AuthorsManager authorsManager;

    @Test
    public void getAllAuthors() {
        List<Author> authors = authorsManager.getAllAuthors().collect(Collectors.toList());
        assertFalse(authors.isEmpty());
        assertEquals(5, authors.size());    // 5!
    }
}

The other test I use DBUnit to add one more, but all five are deleted and only those authors who are in DBUnit are inserted:

@RunWith(SpringRunner.class)
@SpringBootTest
@TestExecutionListeners({
        TransactionalTestExecutionListener.class,
        DependencyInjectionTestExecutionListener.class,
        DbUnitTestExecutionListener.class
})
@DatabaseSetup("/dbunit/books_authors.xml") // add dbunit file
public class AuthorsManagerTest {

    @Autowired
    private AuthorsManager authorsManager;

    @Test
    public void getAllAuthors() {
        List<Author> authors = authorsManager.getAllAuthors().collect(Collectors.toList());
        assertFalse(authors.isEmpty());
        assertEquals(1, authors.size());    // only one!
    }
}

DBUnit file:

<dataset>
    <Authors id="200" name="My Author" />
</dataset>

How to configure DBUnit so that it does not delete the data that is already present, but only supplements it? Because there are test conditions when you only need to add one more entry to the already existing ones


Solution

  • Try using following:

    @DatabaseSetup("/dbunit/books_authors.xml", type = DatabaseOperation.INSERT)
    

    sinse you are not setting any type, you are using the default value for that field, which is CLEAN_INSERT.

    Source: JavaDoc