Search code examples
javadbunitspring-test-dbunit

How to solve foreign key constraint violation issue when using springtestdbunit?


I have two tables, one of table A's fields references table B's field, I use annotation @DatabaseSetup to do the importing of xml file, and I wrote both table A and table B's data in the dataset in the xml file. when I run the unit test, it says INSERT on table A caused a violation of foreign key constraint for key(0).

how to express the reference relationship between the two tables?


Solution

  • I presume your dataset XML file looks something along the lines of:

    <TABLE_A ID="1"/>

    <TABLE_B ID="1" TABLE_A_ID="1"/>

    This violation could occur if:

    • Your second row contains an value for the foreign key reference that doesnt exist e.g.

    <TABLE_A ID="1"/>

    <TABLE_B ID="1" TABLE_A_ID="2"/>

    • Your dataset file inserts the rows in the wrong order e.g:

    <TABLE_B ID="1" TABLE_A_ID="1"/>

    <TABLE_A ID="1"/>

    If you provide your dataset file and Db Unit Test I can be more specific