Search code examples
c#testingintegration-testingxunitxunit.net

How can I create and delete a database at the first and at the end of a Fact in XUnit testing?


In testing some services that connected to the database in integration tests I need to create a single database for a fact and after finish the fact I need to delete that database because in XUnit ,tests are parallel and this can effect to each other for example you wanna edit a user in database in a fact but before this fact there is an other fact has deleted that user and this make my test failed so I need to create a single database for each fact and after finish that fact I want to dispose that database

How can I do this ?


Solution

  • There are different solutions to this issue. But they all boil down to removing the shared resource.

    1. Remove parallelization for xUnit : You can do that by adding a a xunit.runner.json and add parallelizeTestCollections to that file as described in the documentation and you can use Respawn along with that to restore the database to a checkpoint after each test. If you have a lot of tests, then this solution may be slow but can be faster than firing up a db each time. (this is not advisable, see @RubenBartelink answer below)

    2. If there is no relation between the two users of each test then you can use a different Identifier for each user and make the test independent of each others.

    3. If the test is not about integration with the db, than you can use an memory database.

    4. And last, you can use a docker image of the db, perhaps varying one of the connection parameters in order to make each test target an individual database or schema etc.