I am trying to implement integration tests in Asp.Net Core 6. I am trying to use a different database for testing as well as overriding endpoint authentication using the AllowAnonymousFilter. I am following this turorial.
The goal is to override the "ConnectionStrings" property in appsettings.json in the main project with the contents in integrationsettings.json. The contents from integrationtests.json shows up in api.Configuration.Providers[0].Data, so reading of that file seems to work. The actual appsettings.json is formatted the same way but with real data. However, the test still runs with the standard database.
The AllowAnonymousFilter does not work. Since this endpoint requires authorization I get a 401 code. I am new to dotnet and I don't really know how to troubleshoot this...
Test:
public class UserControllerIntegrationTests
{
[Fact]
public async Task Get_ReturnsUserFromDbAsync()
{
var api = new ApiWebApplicationFactory();
var client = api.CreateClient();
var response = await client.GetStringAsync("api/user?id=08da26ac-9de8-4cd8-8ca9-ce21f4952a6d");
var result = JsonConvert.DeserializeObject<UserDto>(response);
Assert.Equal("FirstName", result.FirstName);
}
}
ApiWebApplicationFactory:
internal class ApiWebApplicationFactory : WebApplicationFactory<Program>
{
public IConfiguration Configuration { get; private set; }
protected override void ConfigureWebHost(IWebHostBuilder builder)
{
builder.ConfigureAppConfiguration(config =>
{
Configuration = new ConfigurationBuilder()
.AddJsonFile("integrationsettings.json")
.Build();
config.AddConfiguration(Configuration);
});
builder.ConfigureTestServices(services =>
{
MvcServiceCollectionExtensions.AddMvc(services, options => options.Filters.Add(new AllowAnonymousFilter()));
});
}
}
integrationsettings.json:
{
"ConnectionStrings": {
"Database": "Server=testserver;Database=testserver;User=testserver;Password=testserver;"
}
}