The setup of your test context in XUnit is typically done through the constructor. For context cleanup, you can add the IDisposable
interface to your test class, and put the cleanup code in the Dispose()
method.
But what if your setup/teardown logic contains some async methods? It would certainly be an anti-pattern to add this code inside your synchronous constructor or Dispose.
The correct way to do this in XUnit is through the IAsyncLifetime interface:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
namespace Xunit | |
{ | |
/// <summary> | |
/// Used to provide asynchronous lifetime functionality. Currently supported: | |
/// - Test classes | |
/// - Classes used in <see cref="IClassFixture{TFixture}"/> | |
/// - Classes used in <see cref="ICollectionFixture{TFixture}"/>. | |
/// </summary> | |
public interface IAsyncLifetime | |
{ | |
/// <summary> | |
/// Called immediately after the class has been created, before it is used. | |
/// </summary> | |
Task InitializeAsync(); | |
/// <summary> | |
/// Called when an object is no longer needed. Called just before <see cref="IDisposable.Dispose"/> | |
/// if the class also implements that. | |
/// </summary> | |
Task DisposeAsync(); | |
} | |
} |
This interface provides you an async alternative to manage the lifetime of your test context. It can be used inside your test classes directly but also works in Class and Collection fixtures.