Question

I need an idea/tip how to use DbUnit to assert IDs, generated by a database (e.g. MySQL's auto increment column). I have very simple case, which yet, at the moment, I find problematic:

2 tables: main and related. main.id column is an auto-increment. Related table has a foreign key to it: related.main_id -> main.id. In my test case my application does insert multiple entries into both tables, so the dataset looks similar to this:

<dataset>
    <main id="???" comment="ABC" />
    <main id="???" comment="DEF" />

    <related id="..." main_id="???" comment="#1 related to ABC" />
    <related id="..." main_id="???" comment="#2 related to ABC" />
    <related id="..." main_id="???" comment="#3 related to DEF" />
    <related id="..." main_id="???" comment="#4 related to DEF" />
</dataset>

As the order, how the inserts will be performed is unclear - I cannot simply clear/truncate the table before the test and use predefined IDs in advance (e.g. "ABC" entry will come at first so it gets ID 1 and "DEF" as 2nd - gets 2). If I write test such way - this will be wrong - with a bit of luck sometimes it may work and in other cases not.

Is there a clean way how test such cases? As I still want to assert that entries were created and linked properly in DB, not only that they exists (if I would simply ignore the auto-increment columns).

Was it helpful?

Solution

Based on the comments of the question, I am answering my own question, so this may help others, looking for similar solution.

After all we did skip asserting generated IDs, as they were not really interesting for us. What we actually did want to check is that the entries between main and related tables are "properly linked". To achieve this, in our unit test we did created the the dataset using query, joining both tables:

SELECT main.comment, related.comment AS related_comment 
FROM main, related 
WHERE main.id = related.main_id

Then we assert, that dataset produced by this query matches statically defined dataset:

<dataset>
     <result comment="ABC" related_comment="#1 related to ABC" />
     <result comment="ABC" related_comment="#2 related to ABC" />
     <result comment="DEF" related_comment="#3 related to DEF" />
     <result comment="DEF" related_comment="#4 related to DEF" />
</dataset>

When the datasets are matching, we can assume, that entries were "linked properly".

OTHER TIPS

Maybe you let dbunit sort your table main by id and table related by id automatically. Since the absolute number of rows are known in advantage this should solve your problem.

DBUnit allows sorting with org.dbunit.dataset.SortedTable.SortedTable which needs a table an a list of colums which should be sorted. JavaDoc of SortedTable

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top