springtestdbunit / spring-test-dbunit

Integration between the Spring testing framework and DBUnit
http://springtestdbunit.github.com/spring-test-dbunit/
Apache License 2.0
475 stars 238 forks source link

Foreign Key Contstaint Violations when not using every Table in datasets.xml #100

Closed sijakubo closed 8 years ago

sijakubo commented 8 years ago

Hi there,

i came across an error in your implementation about cleaning the database before Test executing. The following Setup will always end in a JdbcSQLException: "Referential integrity constraint violation" Error, when the order of the test execution is as describe below.

TestClassA datasets.xml contains:

SHOP
CUSTOMER (references Shop)

TestClassB datasets.xml contains:

SHOP

The DbUnitTestExecutionListener will delete every entry in the tables mentioned in the datasets.xml. The first class contains Shops and Customers. Customers reference Shop. Therefore, Shop and Customer will be cleaned. The Second Class then will detect Shop and tries to clean the table which will cause an "Referential integrity constraint violation", because the DB-Entries from the Test before are still there.

(Workaround: insert a Customer in the second datasets.xml, so the DbUnitTestExecutionListener will clean this table as well).

philwebb commented 8 years ago

I'm not sure there's much we can do about that. You need to structure your tests to leave the database in a consistent state. I'd recommend using transactional tests that roll back after each run.

swathistudyblue commented 6 years ago

Isn't theresomething we could do similar like below https://dzone.com/articles/solve-foreign-key-problems ?

gavenkoa commented 1 year ago

http://springtestdbunit.github.io/spring-test-dbunit/faq.html contains the trick with @DatabaseTearDown(value = ...) so in your additional fixtures file you just mention "empty" tables in order they need to be created - to in the reverse order they will be deleted! Like:

<?xml version="1.0" encoding="UTF-8"?>
<dataset>
    <author/>
    <book/>
    <order/>
</dataset>

This list could include missing tables in original fixtures!