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.
XunitTestFramework
classThe 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:
_19using Xunit.Abstractions;_19using Xunit.Sdk;_19_19namespace XUnit.Startup.Dispose.Hooks;_19_19public 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.
TestFramework
classWe'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.
As you can see in the video below, this is how the code will be called when running a test session:
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 😊.