Skip to content

Integrating with TUnit

Like other testing frameworks, you'll want to reuse the IAlbaHost across tests and test fixtures because AlbaHost is relatively expensive to create. To do that with TUnit, you should start by writing a bootstrapping class that inherits from IAsyncInitializer and IAsyncDisposable:

cs
public sealed class AlbaBootstrap : IAsyncInitializer, IAsyncDisposable
{
    public IAlbaHost Host { get; private set; } = null!;

    public async Task InitializeAsync() 
    {
        Host = await AlbaHost.For<WebApp.Program>();
    }

    public async ValueTask DisposeAsync()
    {
        await Host.DisposeAsync();
    }
}

snippet source | anchor

Then inject the instance by added [ClassDataSource<AlbaBootstrap>(Shared = SharedType.Globally)] to your test class. We recommend creating a base class to allow easier access of the host and any other dependencies.

cs
public abstract class AlbaTestBase(AlbaBootstrap albaBootstrap)
{
    protected IAlbaHost Host => albaBootstrap.Host;
}

[ClassDataSource<AlbaBootstrap>(Shared = SharedType.Globally)]
public class MyTestClass(AlbaBootstrap albaBootstrap) : AlbaTestBase(albaBootstrap)
{
    [Test]
    public async Task happy_path()
    {
        await Host.Scenario(_ =>
        {
            _.Get.Url("/fake/okay");
            _.StatusCodeShouldBeOk();
        });
    }
}

snippet source | anchor