A custom XUnit fixture class library that wraps Microsoft.AspNetCore.Mvc.Testing.WebApplicationFactory to simplify behavioral testing in ASP.NET Core applications. Provides easy mock configuration, service replacement, and reusable test contexts.
$ dotnet add package Frinkware.Testing.WebApplicationFactoryA NuGet package that provides a custom XUnit fixture class library for behavioral testing in ASP.NET Core applications. This library wraps Microsoft.AspNetCore.Mvc.Testing.WebApplicationFactory to simplify test setup, mock configuration, and test context reuse.
dotnet add package Frinkware.Testing.WebApplicationFactory
using Frinkware.Testing.WebApplicationFactory;
using Xunit;
public class MyApiTests : IClassFixture<BehavioralTestContextFixture<Startup>>
{
private readonly HttpClient _httpClient;
private readonly Mock<IMyService> _myServiceMock;
public MyApiTests(BehavioralTestContextFixture<Startup> fixture)
{
// Mock out your dependencies
_myServiceMock = fixture.Mock<IMyService>();
_myServiceMock
.Setup(x => x.GetDataAsync())
.ReturnsAsync("test data");
// Create an HTTP client
_httpClient = fixture.CreateClient();
}
[Fact]
public async Task MyEndpoint_ShouldReturnExpectedData()
{
// Act
var response = await _httpClient.GetAsync("/api/myendpoint");
// Assert
response.EnsureSuccessStatusCode();
var content = await response.Content.ReadAsStringAsync();
Assert.Contains("test data", content);
}
}
public MyApiTests(BehavioralTestContextFixture<Startup> fixture)
{
// Use WithDefault to automatically set return values for any method returning this type
_myServiceMock = fixture.Mock<IMyService>()
.WithDefault(() => myDefaultData);
_httpClient = fixture.CreateClient();
}public class CustomFixture : BehavioralTestContextFixture<Startup>
{
protected override Dictionary<string, object>? CommandLineArguments()
{
return new Dictionary<string, object>
{
{ "ConnectionStrings:DefaultConnection", "test-connection-string" }
};
}
}
public class MyTests : IClassFixture<CustomFixture>
{
// Your tests here
}Extends Microsoft.AspNetCore.Mvc.Testing.WebApplicationFactory with:
XUnit class fixture that:
Mock<T>(): Create and register mocks with the test servicesWithDefault<T, TReturn>(): Set default return values for mock methodsResetBehavioral(): Reset mocks including custom default value providersReplaceAllWithSingleton<T>(): Replace all service registrations with a singletonThis library is based on the behavioral testing patterns from the BehavioralTesting repository by Jose-A-ProfessorFrink.
MIT
Contributions are welcome! Please feel free to submit issues or pull requests. This project contains code to facilitate behavioral testing using Moq and the WebApplicationFactory.