While reviewing some XUnit unit tests, I noticed the usage of the [Collection] attribute.
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 theDispose()
method.
- Create the collection definition class, decorating it with the
[CollectionDefinition]
attribute, giving it a unique name that will identify the test collection. AddICollectionFixture<>
to the collection definition class.
- 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.