Codebelt
v12.0.2

Codebelt.Extensions.Xunit.App

One package reference to unlock the full xUnit extensions ecosystem for unit testing, generic host testing, and ASP.NET Core integration testing.

.NET 10.0 / .NET 9.0 MIT 61,852 downloads

Overview

Codebelt.Extensions.Xunit.App is a metadata-only convenience package that brings together the three standalone xUnit extension packages under a single reference. Version 12.0.0 aligns the bundled toolchain with xUnit.v3 4.0.0 and targets test projects that need the full Codebelt xUnit toolchain: the foundational Test base class and in-memory test store, the generic host and DI testing infrastructure, and the ASP.NET Core integration testing layer built on TestServer.

Adding this package to a test project pulls in Codebelt.Extensions.Xunit, Codebelt.Extensions.Xunit.Hosting, and Codebelt.Extensions.Xunit.Hosting.AspNetCore. The package itself declares no public API; every type, base class, factory, and extension method comes from the referenced packages.

Key APIs

This package exposes no additional public APIs. The consumer-facing APIs come from the three referenced packages:

Test (from Codebelt.Extensions.Xunit) is the abstract base class for all Codebelt-style xUnit tests. It accepts an ITestOutputHelper in its constructor, exposes TestOutput for diagnostic writing, and provides lifecycle hooks through OnDisposeManagedResources, OnDisposeManagedResourcesAsync, and OnDisposeUnmanagedResources. The static Match method supports wildcard-based string comparison with configurable options.

InMemoryTestStore<T> (from Codebelt.Extensions.Xunit) implements ITestStore<T> and provides a simple in-memory collection for test data. It supports Add, Query with an optional predicate, and QueryFor<TResult> for type-filtered retrieval.

ApplicationTestFactory (from Codebelt.Extensions.Xunit.Hosting) creates IHostTest instances that bootstrap an existing .NET application entry point. It resolves the host builder or host factory from the entry point assembly and starts the host, making the Host, Configuration, and Environment properties available for assertions.

WebApplicationTestFactory (from Codebelt.Extensions.Xunit.Hosting.AspNetCore) extends the application entry-point pattern to ASP.NET Core. Its Create method returns an IHostTest backed by a TestServer, while RunAsync creates a host and executes a response factory against an in-memory HttpClient in a single call.

Basic usage

Codebelt.Extensions.Xunit

using Codebelt.Extensions.Xunit;
using Xunit;

namespace MyProject.Tests;

public class OrderProcessor
{
    public record OrderResult(string OrderId, int ItemCount, decimal Total);

    public OrderResult Process(System.Collections.Generic.IEnumerable<(string Name, int Qty, decimal Price)> items)
    {
        var itemList = new System.Collections.Generic.List<(string Name, int Qty, decimal Price)>();
        foreach (var item in items) { itemList.Add(item); }
        var total = 0m;
        foreach (var item in itemList) { total += item.Qty * item.Price; }
        return new OrderResult(System.Guid.NewGuid().ToString("N"), itemList.Count, total);
    }
}

public class OrderProcessorTest : Test
{
    private readonly OrderProcessor _processor = new();

    public OrderProcessorTest(ITestOutputHelper output) : base(output)
    {
    }

    [Fact]
    public void Process_MultipleItems_ReturnsCorrectTotalAndCount()
    {
        var result = _processor.Process(new[]
        {
            ("Widget", 3, 9.99m),
            ("Gadget", 1, 24.50m),
            ("Doohickey", 2, 4.75m)
        });

        TestOutput.WriteLine($"Count: {result.ItemCount}");
        TestOutput.WriteLines($"OrderId: {result.OrderId}", $"Total: {result.Total}");

        Assert.Equal(3, result.ItemCount);
        Assert.Equal(63.97m, result.Total);
        Assert.True(Match("OrderId: *", $"OrderId: {result.OrderId}"));
    }
}

Use this pattern when writing unit tests that need a structured base class with lifecycle hooks and diagnostic output. The Test base class standardizes test construction and disposal across the entire test suite.

Codebelt.Extensions.Xunit.Hosting

using Codebelt.Extensions.Xunit;
using Codebelt.Extensions.Xunit.Hosting;
using Microsoft.Extensions.DependencyInjection;
using Xunit;

namespace MyProject.Tests;

public class HostTestFactoryTest : Test
{
    public HostTestFactoryTest(ITestOutputHelper output) : base(output)
    {
    }

    [Fact]
    public void Create_WithServiceRegistration_ResolvesScopedService()
    {
        using var hostTest = HostTestFactory.Create(services =>
        {
            services.AddSingleton<IMarker, Marker>();
            services.AddXunitTestLogging(TestOutput);
        });

        var marker = hostTest.Host.Services.GetRequiredService<IMarker>();

        TestOutput.WriteLine($"Environment: {hostTest.Environment.EnvironmentName}");
        TestOutput.WriteLine($"Marker value: {marker.Value}");

        Assert.NotNull(marker);
        Assert.Equal("Hosting", marker.Value);
        Assert.Equal("Development", hostTest.Environment.EnvironmentName);
    }

    private interface IMarker { string Value { get; } }
    private class Marker : IMarker { public string Value => "Hosting"; }
}

Use this pattern when testing components that depend on Microsoft Dependency Injection without requiring a full web host. HostTestFactory.Create builds a host from the provided service and host configuration delegates, giving access to IHost, IConfiguration, and IHostEnvironment.

Codebelt.Extensions.Xunit.Hosting.AspNetCore

using Codebelt.Extensions.Xunit;
using Codebelt.Extensions.Xunit.Hosting.AspNetCore;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Xunit;

namespace MyProject.Tests;

public class WebHostTestFactoryTest : Test
{
    public WebHostTestFactoryTest(ITestOutputHelper output) : base(output)
    {
    }

    [Fact]
    public async Task RunAsync_WithEndpointMapping_ReturnsConfiguredResponse()
    {
        using var response = await WebHostTestFactory.RunAsync(
            services =>
            {
                services.AddRouting();
            },
            app =>
            {
                app.UseRouting();
                app.UseEndpoints(endpoints =>
                {
                    endpoints.MapGet("/", async context =>
                    {
                        await context.Response.WriteAsync("ready");
                    });
                });
            },
            responseFactory: client => client.GetAsync("/"));

        var body = await response.Content.ReadAsStringAsync();

        TestOutput.WriteLine($"Status: {response.StatusCode}");
        TestOutput.WriteLine($"Body: {body}");

        Assert.True(response.IsSuccessStatusCode);
        Assert.Equal("ready", body);
    }
}

Use this pattern when testing ASP.NET Core middleware, filters, or request pipelines in isolation. WebHostTestFactory.RunAsync spins up an in-memory TestServer, configures services and the application pipeline, executes the response factory, and returns the HttpResponseMessage for assertions.

Codebelt.Extensions.Xunit.App provides a single package reference while all APIs come from the three referenced packages. This eliminates the need to manage individual package references when a test project requires the full Codebelt xUnit toolchain spanning unit testing, generic host integration, and ASP.NET Core test server scenarios.

Installation

dotnet add package Codebelt.Extensions.Xunit.App

Usage guidance

Reach for Codebelt.Extensions.Xunit.App when a test project needs the complete Codebelt xUnit.v3 4 stack: the Test base class, in-memory test stores, generic host and DI testing, and ASP.NET Core TestServer integration. A single package reference replaces three individual references and keeps the test project aligned with the full ecosystem. When a test project only needs basic unit testing without hosting concerns, Codebelt.Extensions.Xunit alone is the better fit.

Family packages