roninforge/roninforge-aspnet/aspnet-testing-setup

Claude Code and agent skill by roninforge/roninforge-aspnet

Trust tier 3
  • community
Source check pending

Checking that the SKILL.md file is still in the repository.

Wire up an xUnit + WebApplicationFactory + Testcontainers test project for ASP.NET Core 9. Covers Postgres/Redis containers, ConfigureTestServices to swap dependencies, MockHttpMessageHandler for typed HttpClient, FluentAssertions for readable tests.

Install

npx vskill@latest install roninforge/roninforge-aspnet/aspnet-testing-setup

SKILL.md

The same SKILL.md was published earlier as roninforge/roninforge-aspnet/aspnet-testing-setup.

Set up ASP.NET Core 9 Testing

When to Use

When adding integration tests to a new or existing ASP.NET Core 9 project, or replacing brittle unit tests with in-process integration via WebApplicationFactory.

Instructions

Step 1: Create the test project
bash
dotnet new xunit -o MyApi.Tests
dotnet add MyApi.Tests reference ./MyApi

Add packages:

bash
dotnet add MyApi.Tests package Microsoft.AspNetCore.Mvc.Testing
dotnet add MyApi.Tests package FluentAssertions
dotnet add MyApi.Tests package Testcontainers.PostgreSql
dotnet add MyApi.Tests package Testcontainers.Redis # if needed
Step 2: Expose Program as a partial class

In Program.cs, add at the very bottom:

csharp
// expose for WebApplicationFactory<Program>
public partial class Program;

Without this, WebApplicationFactory<Program> cannot find a TEntryPoint because top-level Program.cs makes the type internal.

Step 3: Database fixture with Testcontainers
csharp
// DbFixture.cs
public sealed class DbFixture : IAsyncLifetime {
public PostgreSqlContainer Container { get; } = new PostgreSqlBuilder()
.WithImage("postgres:16-alpine")
.Build();
public Task InitializeAsync() => Container.StartAsync();
public Task DisposeAsync() => Container.DisposeAsync().AsTask();
}
[CollectionDefinition(nameof(IntegrationTests))]
public sealed class IntegrationTests : ICollectionFixture<DbFixture> { }

The collection definition makes the fixture singleton across all classes that opt in via [Collection(nameof(IntegrationTests))].

Step 4: Custom WebApplicationFactory
csharp
public sealed class TestFactory(DbFixture db) : WebApplicationFactory<Program> {
protected override void ConfigureWebHost(IWebHostBuilder builder) {
builder.UseSetting("ConnectionStrings:Db", db.Container.GetConnectionString());
builder.ConfigureTestServices(services => {
services.AddSingleton<IPaymentGateway, StubPaymentGateway>(); // swap external
});
}
}

The factory inherits the real Program.cs configuration and overrides only what the tests need.

Step 5: First test
csharp
[Collection(nameof(IntegrationTests))]
public sealed class OrdersApiTests(DbFixture db) : IAsyncLifetime {
private TestFactory _factory = null!;
private HttpClient _client = null!;
public async Task InitializeAsync() {
_factory = new TestFactory(db);
_client = _factory.CreateClient();
using var scope = _factory.Services.CreateScope();
var ctx = scope.ServiceProvider.GetRequiredService<AppDb>();
await ctx.Database.MigrateAsync();
}
public Task DisposeAsync() {
_factory.Dispose();
return Task.CompletedTask;
}
[Fact]
public async Task GetOrder_returns_NotFound_when_missing() {
var resp = await _client.GetAsync("/api/orders/999");
resp.StatusCode.Should().Be(HttpStatusCode.NotFound);
}
[Fact]
public async Task CreateOrder_returns_Created_and_dto() {
var req = new CreateOrder("SKU-1", 3);
var resp = await _client.PostAsJsonAsync("/api/orders", req);
resp.StatusCode.Should().Be(HttpStatusCode.Created);
var dto = await resp.Content.ReadFromJsonAsync<OrderDto>();
dto!.Sku.Should().Be("SKU-1");
dto.Quantity.Should().Be(3);
}
}
Step 6: Mocking outbound HTTP

For a typed client (PaymentClient) you can swap the underlying HttpMessageHandler:

csharp
public sealed class StubHandler(int status, string body) : HttpMessageHandler {
protected override Task<HttpResponseMessage> SendAsync(
HttpRequestMessage req, CancellationToken ct) {
return Task.FromResult(new HttpResponseMessage((HttpStatusCode)status) {
Content = new StringContent(body, Encoding.UTF8, "application/json")
});
}
}
// In TestFactory.ConfigureTestServices
services.AddHttpClient<PaymentClient>().ConfigurePrimaryHttpMessageHandler(
_ => new StubHandler(200, """{"id":"ch_1"}"""));
Step 7: Async assertions and lifecycle

xUnit conventions:

  • [Fact] for parameterless tests, [Theory] + [InlineData] for table-driven.
  • Test methods return Task and are awaited internally.
  • AAA (Arrange, Act, Assert) with blank lines between sections.
  • One logical assertion per test (a fluent chain counts as one).
Step 8: CI considerations

Pin container image tags in CI (postgres:16-alpine, not postgres). Pre-pull images at the start of the workflow to amortize startup:

yaml
- run: docker pull postgres:16-alpine
- run: dotnet test --logger "console;verbosity=normal"

Anti-patterns to avoid

  • Microsoft.EntityFrameworkCore.InMemory for tests that simulate Postgres - SQL dialect mismatches hide real bugs. Use Testcontainers.
  • Mocking DbContext. Always use a real database (Testcontainers).
  • One container per test class without IClassFixture / ICollectionFixture - each test class starts a new container, which is slow.
  • Thread.Sleep in async tests. Use Task.Delay(_, ct) or await whatever you are waiting for.
  • Skipping DatabaseMigrateAsync() in test setup - the schema does not exist on a fresh container.

Security

  • Security scanPassed, 100 of 100Pattern checks on the skill's files.
  • Model reviewPassed

Quality evaluation

  • Task evaluationNot runNo evaluation yet. Run one in Skill Studio.

Source

Popularity

7-day trend score
5

Not refreshed yet.

Works with

Any agent vskill installs to: 56 targets in all. These 39 have a page on this site.

  • Claude Code
  • Cursor
  • GitHub Copilot
  • Windsurf
  • Codex
  • Gemini CLI
  • Cline
  • Amp
  • Roo Code
  • Goose
  • Continue
  • Kilo Code
  • Junie
  • Trae
  • OpenHands
  • Qwen Code
  • AI Agent
  • Tabnine Chat
  • Sourcegraph Cody
  • Amazon Q
  • Firebase Genkit
  • Sweep
  • Devin
  • Phind
  • Mentat
  • Claude Desktop
  • Aider
  • GPT Pilot
  • Plandex
  • bolt.new
  • v0
  • Replit Agent
  • Anse
  • TypingMind
  • BetterChatGPT
  • LibreChat
  • Warp AI
  • Pieces
  • Fig AI
Embed badge
vskill VERIFIED badge
[![vskill VERIFIED](https://verified-skill.com/api/v1/skills/roninforge/roninforge-aspnet/aspnet-testing-setup/badge)](https://verified-skill.com/skills/roninforge/roninforge-aspnet/aspnet-testing-setup)

Something wrong with this skill or its page? Tell us.