How to hook into xUnit.net test session startup and teardown

2024/02/10

Usually you would use a test fixture in xUnit.net when wanting to run logic before and after tests have run. But what if you want to hook into when a test session starts and ends? A test session being from when your selected tests are run till they are done. This can be relevant in some cases where you might have to use complex or expensive setup and teardown logic. This guide will show you how to hook into a test session's beginning and end.

Creating the XunitTestFramework class

The XunitTestFramework class can be inherited as the entrypoint of your test session. By inheriting this class and implementing an IDisposable interface you will have an object that xUnit.net can target as the entrypoint of a test session. Check the code below:


_19
using Xunit.Abstractions;
_19
using Xunit.Sdk;
_19
_19
namespace XUnit.Startup.Dispose.Hooks;
_19
_19
public class TestFramework : XunitTestFramework, IDisposable
_19
{
_19
public TestFramework(IMessageSink messageSink) : base(messageSink)
_19
{
_19
Console.WriteLine("Tests are starting!");
_19
}
_19
_19
public new void Dispose()
_19
{
_19
Console.WriteLine("Tests are done!");
_19
_19
base.Dispose();
_19
}
_19
}

When the test session starts it will enter the constructor and write the "Tests are starting!" line. When the session is over, the Dispose method will be used which will result in the "Test are done!" line being written. Remember to call base.Dispose(); otherwise the base xUnit.net disposal implementation will not happen.

Configuring test project to use the TestFramework class

We've created the logic we want to run, but the test project has not been set up to use this class. It is not enough to just create it, the project won't discover it by itself. To configure it so it will be used, add the following to the .csproj file of the test project:


_10
<ItemGroup>
_10
<AssemblyAttribute Include="Xunit.TestFramework">
_10
<_Parameter1>XUnit.Startup.Dispose.Hooks.TestFramework</_Parameter1>
_10
<_Parameter2>XUnit.Startup.Dispose.Hooks</_Parameter2>
_10
</AssemblyAttribute>
_10
</ItemGroup>

Remember to change the parameter values if your project is called something different or if you've called the inheriting XunitTestFramework class something different.

Behaviour

As you can see in the video below, this is how the code will be called when running a test session:

Conclusion

You should be able to create your own class inheriting XuniTestFramework to hook into the startup and teardown of a test session now. I hope this was able to help you 😊.