Breaking

Thursday, September 2, 2021

XUnit Collection fixtures

While reviewing some XUnit unit tests, I noticed the usage of the [Collection] attribute.

[Collection("Integration test")]
public class ProductApiTests
{
APIFixture fixture;
public ProductApiTests(APIFixture fixture)
{
this.fixture = fixture;
}
}

I didn’t know the attribute. So I took a look at the XUnit documentation and discovered the existence of Collection fixtures. It allows you to create a single test context and share it among tests in several test classes, and have it cleaned up after all the tests in the test classes have finished.

In the code I was reviewing it was used to spin up a test server and shut it down after all tests has been completed.

I don’t find it very intuitive how it should be used but it is well explained in the documentation. In case you are too lazy to click on the link, here are the steps:

  • Create the fixture class, and put the startup code in the fixture class constructor. If the fixture class needs to perform cleanup, implement IDisposable on the fixture class, and put the cleanup code in the Dispose() method.
public class DatabaseFixture : IDisposable
{
public DatabaseFixture()
{
Db = new SqlConnection("MyConnectionString");
// ... initialize data in the test database ...
}
public void Dispose()
{
// ... clean up test data from the database ...
}
public SqlConnection Db { get; private set; }
}
  • Create the collection definition class, decorating it with the [CollectionDefinition] attribute, giving it a unique name that will identify the test collection. Add ICollectionFixture<> to the collection definition class.
[CollectionDefinition("Database collection")]
public class DatabaseCollection : ICollectionFixture<DatabaseFixture>
{
// This class has no code, and is never created. Its purpose is simply
// to be the place to apply [CollectionDefinition] and all the
// ICollectionFixture<> interfaces.
}
  • Add the [Collection] attribute to all the test classes that will be part of the collection, using the unique name you provided to the test collection definition class's [CollectionDefinition] attribute. If the test classes need access to the fixture instance, add it as a constructor argument, and it will be provided automatically.
[Collection("Database collection")]
public class DatabaseTestClass1
{
DatabaseFixture fixture;
public DatabaseTestClass1(DatabaseFixture fixture)
{
this.fixture = fixture;
}
}
[Collection("Database collection")]
public class DatabaseTestClass2
{
// ...
}

No comments:

Post a Comment