在我的 .NET6 项目中,我有一些最小的 API,我想测试它们。您可以在GitHub 上找到完整的源代码。为此,我创建了一个新的 NUnit 测试项目。在项目文件中,我添加PreserveCompilationContext
了,文件看起来像
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<Nullable>enable</Nullable>
<IsPackable>false</IsPackable>
<PreserveCompilationContext>true</PreserveCompilationContext>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.AspNetCore.Mvc.Testing" Version="6.0.1" />
<PackageReference Include="Microsoft.EntityFrameworkCore.InMemory" Version="6.0.1" />
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="17.0.0" />
<PackageReference Include="NUnit" Version="3.13.2" />
<PackageReference Include="NUnit3TestAdapter" Version="4.2.0" />
<PackageReference Include="coverlet.collector" Version="3.1.0" />
</ItemGroup>
<ItemGroup>
<ProjectReference Include="..\src\MinimalApis.csproj" />
</ItemGroup>
</Project>
然后,我像这样创建了 WebApplicationFactory 的实现
class MinimalApisApplication : WebApplicationFactory<Program>
{
protected override IHost CreateHost(IHostBuilder builder)
{
var root = new InMemoryDatabaseRoot();
builder.ConfigureServices(services =>
{
services.RemoveAll(typeof(DbContextOptions<ClientContext>));
services.AddDbContext<ClientContext>(options =>
options.UseInMemoryDatabase("Testing", root));
});
return base.CreateHost(builder);
}
}
最后,我的测试课是这样的
public class Tests
{
[SetUp]
public void Setup()
{
}
[Test]
public async Task GetClients()
{
await using var application = new MinimalApisApplication();
var client = application.CreateClient();
var notes = await client.GetFromJsonAsync<List<ClientModel>>("/clients");
Assert.IsNotNull(notes);
Assert.IsTrue(notes.Count == 0);
}
}
当我运行项目时,我收到一个错误
System.InvalidOperationException:找不到“C:\Projects\Net6MinimalAPIs\MinimalApis.Tests\bin\Debug\net6.0\testhost.deps.json”。此文件是功能测试正常运行所必需的。您的源项目 bin 文件夹中应该有该文件的副本。如果不是这种情况,请确保在项目文件中将属性 PreserveCompilationContext 设置为 true。例如“真实”。要使功能测试正常工作,它们需要从构建输出文件夹运行,或者必须将应用程序输出目录中的 testhost.deps.json 文件复制到运行测试的文件夹中。此错误的一个常见原因是在测试运行时启用了卷影复制。
我用谷歌搜索了一下,但我找不到如何生成这个文件。
更新
我试图添加一个xUnit
具有相同结果的项目。另外,我注意到它Program
来自
using Microsoft.VisualStudio.TestPlatform.TestHost;
因为我添加了这个参考,但这是错误的。我想参考Program
主项目中的 ,但由于它的保护级别,它是不可访问的。Program.cs
外观_
var builder = WebApplication.CreateBuilder(args);
builder.Services.AddDbContext<ClientContext>(opt =>
opt.UseInMemoryDatabase("Clients"));
builder.Services
.AddTransient<IClientRepository,
ClientRepository>();
builder.Services
.AddAutoMapper(Assembly.GetEntryAssembly());
builder.Services.AddEndpointsApiExplorer();
builder.Services.AddSwaggerGen(c =>
{
c.SwaggerDoc("v1", new OpenApiInfo {
Title = builder.Environment.ApplicationName, Version = "v1"
});
});
var app = builder.Build();
app.UseSwagger();
app.UseSwaggerUI(c =>
{
c.SwaggerEndpoint("v1/swagger.json",
$"{builder.Environment.ApplicationName} v1");
});
app.MapFallback(() => Results.Redirect("/swagger"));
// Get a shared logger object
var loggerFactory =
app.Services.GetService<ILoggerFactory>();
var logger =
loggerFactory?.CreateLogger<Program>();
if (logger == null)
{
throw new InvalidOperationException(
"Logger not found");
}
// Get the Automapper, we can share this too
var mapper = app.Services.GetService<IMapper>();
if (mapper == null)
{
throw new InvalidOperationException(
"Mapper not found");
}