Skip to content

Alternative Bootstrapping Methods ​

Whilst AlbaHost.For<T> is the preferred way of bootstrapping, other options exist in Alba to cover some older & alternative scenarios.

Initializing AlbaHost with IHostBuilder Directly ​

To bootstrap a ASP.NET Core Startup.cs-style application, create a AlbaHost using the definition of your IHostBuilder as shown below. On .NET 11 this is the way to test a Startup.cs-style application, because AlbaHost.For<T> only supports applications built with WebApplicationBuilder there.

cs
[Fact]
public async Task build_host_from_Program()    
{
    // Bootstrap your application just as your real application does
    var hostBuilder = Program.CreateHostBuilder(Array.Empty<string>());

    await using var host = await AlbaHost.For(hostBuilder);

    // Just as a sample, I'll run a scenario against
    // a "hello, world" application's root url
    await host.Scenario(s =>
    {
        s.Get.Url("/");
        s.ContentShouldBe("Hello, World!");
    });
}

snippet source | anchor

TIP

Bootstrapping an AlbaHost is asynchronous. Use your test framework's asynchronous initialization support (e.g. xUnit's IAsyncLifetime) to start the host.

Or alternatively, you can use one of the Alba extension methods off of IHostBuilder to start an AlbaHost object in a fluent interface style:

cs
[Fact]
public async Task fluent_interface_bootstrapping()    
{
    await using var host = await Program
        .CreateHostBuilder(Array.Empty<string>())
        .StartAlbaAsync();

    // Just as a sample, I'll run a scenario against
    // a "hello, world" application's root url
    await host.Scenario(s =>
    {
        s.Get.Url("/");
        s.ContentShouldBe("Hello, World!");
    });
}

snippet source | anchor

The AlbaHost is an extension of the standard .Net Core IHost interface with a few additions for testing support. While you can always access the underlying TestServer through the IAlbaHost.Server property, you're mostly going to be using the Scenario() method to write Alba "Scenario" tests.

TIP

Every bootstrapping method returns an AlbaHostBuilder, so configuration values, service registrations, and extensions can be chained on before the host is awaited. See Configuring the Host Fluently.