dotnet / dotnet/aspnetcore

WebApplicationFactory should enable ValidateScopes and ValidateOnBuild by default regardless of environment

Open
#56,411 1 comment 1 reaction 0 assignees View on GitHub
area-minimal area-mvc feature-mvc-testing
Dominant language
C#
Stars
38.4k
Forks
10.9k
Avg merge
2d 6h
Merged PRs (30d)
290

Description

### Is there an existing issue for this?

- [X] I have searched the existing issues

### Is your feature request related to a problem? Please describe the problem.

In the context of `WebApplicationFactory` which is intended for testing, the service provider options `ValidateScopes` and `ValidateOnBuild` are not specifically set, and instead rely on the environment to be Development.

**API Code**: When run in dev mode this throws exception due to invalid DI setup.
```csharp
var builder = WebApplication.CreateBuilder(args);

builder.Services.AddSingleton();
builder.Services.AddScoped();

var app = builder.Build();

app.MapGet("/hello", () => "world");

app.Run();

public class SingletonService(ScopedService scoped) { }
public class ScopedService { }
public partial class Program { }
```

**Test Code**: E2E tests pass
```csharp
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc.Testing;

namespace TestProject;

public class UnitTest1
{
[Fact]
public async Task Hello()
{
var api = new TestApi();
using var client = api.CreateClient();
var response = await client.GetAsync("/hello");
response.EnsureSuccessStatusCode();
var responseContent = await response.Content.ReadAsStringAsync();
Assert.Equal("world", responseContent);
}
}

public class TestApi : WebApplicationFactory
{
protected override void ConfigureWebHost(IWebHostBuilder builder)
{
builder.UseEnvironment("test"); // <-- In E2E test mode I want a different environment
}
}
```

### Describe the solution you'd like

The options `ValidateScopes` and `ValidateOnBuild` should be true by default when using `WebApplicationFactory` which is designed for testing.

### Additional context

This can easily be done manually via the following code. It's just unexpected that this isn't the default.
```csharp
protected override void ConfigureWebHost(IWebHostBuilder builder)
{
builder.UseEnvironment("test");
builder.UseDefaultServiceProvider(options =>
{
options.ValidateScopes = true;
options.ValidateOnBuild = true;
});
}
```

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.