xUnit fixture

Spread the love

What is xUnit fixture

xUnit.net creates a new instance of the test class for every test that is run, so any code which is placed into the constructor of the test class will be run for every single test. This makes the constructor a convenient place to put reusable context setup code where you want to share the code without sharing object instances (meaning, you get a clean copy of the context object(s) for every test that is run).

Project.Tests is the fixture project to be used by different unit test. This fixture share with different unit tests a common logic, for example all unit tests can share the same inMemory context database, without the need to create a new context and fill the database with every unit test call.

Please subscribe to our YouTube channel and stay updated with our new released videos

Please check our post on how to install xUnit framework in .Net 5.0 (Unit testing C#) and create your first unit test

The DatabaseFixture constructor call 2 functions; InitDatabase and FillDatabase

InitDatabase initialize the inMemory context database

While FillDatabase fill the database with data, the data is extracted from the TableLists class model

TableLists contains basic raw data filled manually by the unit test developers.

How to call fixture from a unit test

For a Unit test to use Database fixture, the unit test should simply inherit IClassFixture<DatabaseFixture>

For example, in UnitTests class, we access the fixture as the following:

We can directly call the fixture shared resources, for example we can use the fixture context by calling fixture.context

xUnit fixture cleanup

For context cleanup, add the IDisposable interface to your test class, and put the cleanup code in the Dispose() method.

For any comment or question please share it with us through our contact page

Rpc Technology