ASP.NET Core 6 web API 的集成测试抛出 System.InvalidOperationException

Integration test for ASP.NET Core 6 web API throws System.InvalidOperationException

我正在尝试了解如何在 ASP.NET Core 6 web API 控制器上进行集成测试。我已尝试遵循所有 guides、SO 帖子和我能找到的建议,但出于某种原因,我不断遇到指南中未提及的错误。

EventControllerTests.cs

namespace UnitTests.ProjectToBeTested.Controllers
{
    public class EventControllerTests
    {
        [Fact]
        public async Task EventController_Post_RespondsOkIfRequestContainsCorrectFeilds_SuccessAsync()
        {

            // Arrange
            var application = new WebApplicationFactory<Program>();

            var client = application.CreateClient();
            ...

ProjectToBeTested.csproj

...
    <ItemGroup>
        <InternalsVisibleTo Include="IntegrationTests" />
    </ItemGroup>
...

这会在 运行 测试时抛出以下内容:

Message:  System.InvalidOperationException : No method 'public static IHostBuilder CreateHostBuilder(string[] args)' or 'public static IWebHostBuilder CreateWebHostBuilder(string[] args)' found on 'Program'. Alternatively, WebApplicationFactory`1 can be extended and 'CreateHostBuilder' or 'CreateWebHostBuilder' can be overridden to provide your own instance.

Stack Trace:  WebApplicationFactory1.CreateWebHostBuilder() WebApplicationFactory1.EnsureServer() WebApplicationFactory1.CreateDefaultClient(DelegatingHandler[] handlers) WebApplicationFactory1.CreateDefaultClient(Uri baseAddress, DelegatingHandler[] handlers) WebApplicationFactory1.CreateClient(WebApplicationFactoryClientOptions options) WebApplicationFactory1.CreateClient() EventControllerTests.EventController_Post_RespondsOkIfRequestContainsCorrectFeilds_SuccessAsync() line 17 --- End of stack trace from previous location ---

显示为一个可能的解决方案,但使用启动 class 使用 pre-6。 .NET 6 解决方案是什么?

如果我改为遵循 "Basic tests with the default WebApplicationFactory"-guide 我什至无法构建解决方案,因为测试 class 构造函数抛出

Error CS0051 Inconsistent accessibility: parameter type 'WebApplicationFactory' is less accessible than method 'EventControllerTests.EventControllerTests(WebApplicationFactory)' IntegrationTests C:\...\EventControllerTests.cs

我无法重现这个。我使用

在 .NET 6 RC1 上从命令行创建了两个新项目
dotnet new webapi -o webapi1
dotnet new xunit -o test1
dotnet new sln

Web API 项目

我对 Web API 项目所做的唯一更改是将其添加到项目文件中:

  <ItemGroup>
    <InternalsVisibleTo Include="test1" />
  </ItemGroup>

Program.cs保持不变:

using Microsoft.OpenApi.Models;

var builder = WebApplication.CreateBuilder(args);

// Add services to the container.

builder.Services.AddControllers();
builder.Services.AddSwaggerGen(c =>
{
    c.SwaggerDoc("v1", new() { Title = "webapi2", Version = "v1" });
});

var app = builder.Build();

// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI(c => c.SwaggerEndpoint("/swagger/v1/swagger.json", "webapi2 v1"));
}

app.UseHttpsRedirection();

app.UseAuthorization();

app.MapControllers();

app.Run();

测试项目

在测试项目中,我添加了对 webapi1Microsoft.AspNetCore.Mvc.Testing 包的引用。

我把Unit1.cs改成了

using Microsoft.AspNetCore.Mvc.Testing;
using Xunit;
using webapi2;

namespace test1;

public class UnitTest1
{
    [Fact]
    public void Test1()
    {
        using var app = new WebApplicationFactory<Program>();
        using var client=app.CreateClient();
    }
}

项目编译和测试运行成功。

解法:

这是因为测试项目的 Microsoft.AspNetCore.Mvc.Testing 包使用了错误的版本(它使用的是版本 5.*)。确保您使用适合 .NET 6 的版本。截至目前,有适合我的 6.0.0-rc.2.21480.10 版本。