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

Time:12-24

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 ?

CodePudding user response:

Use a Collection Fixture. This addresses your needs by:

  1. only letting one test that needs the resource use it at a time
  2. allowing you to do a single spin up/down per overall test run

CodePudding user response:

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 user Respawn a long with that to bring back the database to a checkpoint after each test. If you have a lot of tests than this solution maybe 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 in memory database.

  4. And last, you can use a docker image of the db and maybe varying one of the connection parameters in order to make the db exclusive for each test.

  • Related