[英].NET 6 TestServer cannot resolve Controller
I have a .NET 6 minimal API, and I'm using WebApplicationFactory<T>
for integration testing.我有一个 .NET 6 最小 API,我正在使用WebApplicationFactory<T>
进行集成测试。 Usually, I have something roughly like this in my tests:通常,我的测试中大致有这样的东西:
using TestServer server = new WebApplicationFactory<Program>().Server;
using HttpClient client = server.CreateClient();
// ... do stuff with the client
However, I would like to also test my controller directly (primarily so that I can use the debugger within the controller itself during the tests), after getting an instance of it with all the DI goodness baked in from the factory, but it throws an exception when I try to resolve my controller, like this:但是,我还想直接测试我的控制器(主要是为了在测试期间我可以在控制器本身内使用调试器),在获得一个带有工厂所有 DI 优点的实例之后,但它抛出了一个当我尝试解析我的控制器时出现异常,如下所示:
using TestServer server = new WebApplicationFactory<Program>().Server;
// throws InvalidOperationException : No service for type 'MyController' has been registered.
var controller = server.Services.GetRequiredService<MyController>();
Why is this happening, and is there a way to fix it?为什么会发生这种情况,有没有办法解决它?
Of course, I have a line in Program.cs
like this:当然,我在Program.cs
中有这样一行:
builder.Services.AddControllers();
...and my API starts up correctly and the controller in question works in this case. ...并且我的 API 正确启动并且有问题的控制器在这种情况下工作。
Not a perfect solution, but this worked:不是一个完美的解决方案,但这有效:
Microsoft.AspNetCore.Mvc.Core
1 - 添加Microsoft.AspNetCore.Mvc.Core
dotnet add package Microsoft.AspNetCore.Mvc.Core
using TestServer server = new WebApplicationFactory<Program>()
.WithWebHostBuilder(builder =>
{
builder.ConfigureServices(services =>
{
services.AddMvc().AddControllersAsServices();
}
})
.Server;
// now this works
var controller = server.Services.GetRequiredService<MyController>();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.