Skip to content

A lightweight and extensible base class for writing web integration tests in ASP.NET Core for HamedStack framework.

License

Notifications You must be signed in to change notification settings

HamedStack/HamedStack.WebIntegrationTest

Repository files navigation

🧪 Web Integration Test Base for ASP.NET Core

This library provides a reusable, abstract base class for writing clean and consistent web integration tests in ASP.NET Core applications. It streamlines setup for HttpClient, CQRS dispatching, and EF Core DbContext access—empowering you to write robust end-to-end tests quickly.


✨ Features

  • ✅ Automatically sets up HttpClient for HTTP request testing.
  • ✅ Provides scoped access to EF Core DbContext for direct DB assertions.
  • ✅ Supports CQRS via ICommandQueryDispatcher.
  • ✅ Easily configurable with a custom WebApplicationFactory<T> using in-memory DB.

✅ Your Custom Web Application Factory

public class IntegrationTestWebAppFactory : WebApplicationFactory<Program>
{
    protected override void ConfigureWebHost(IWebHostBuilder builder)
    {
        builder.ConfigureTestServices(services =>
        {
            services.RemoveAll(typeof(DbContextOptions<MyDbContext>));

            services.AddDbContext<MyDbContext>((_, options) =>
            {
                options.UseInMemoryDatabase("MyDb");
            });

            using var scope = services.BuildServiceProvider().CreateScope();
            var db = scope.ServiceProvider.GetRequiredService<MyDbContext>();
            db.Database.EnsureCreated();

            builder.UseEnvironment("Development");
        });
    }
}

✅ Writing a Test

public class MyIntegrationTests : WebIntegrationTestBase<Program, MyDbContext>
{
    // Passing your custom WebApplicationFactory to constructor.
    public MyIntegrationTests() : base(new IntegrationTestWebAppFactory())
    { }

    [Fact]
    public async Task ShouldReturnSuccessWhenCreated()
    {
        var output = await Dispatcher.Send(new CreateMyCommand
        {
            Name = "test",
            UpperWarningLimit = 20,
            LowerWarningLimit = 10,
            Location = "test_location"
        });

        output.IsSuccess.Should().BeTrue();
        output.Value.Should().NotBeEmpty();
    }
}

Releases

No releases published

Packages

No packages published

Languages