r .*_* .r 7 c# xunit asp.net-core .net-6.0
我试图了解如何在 ASP.NET Core 6 Web API 控制器上进行集成测试。我尝试遵循我能找到的所有指南、帖子和建议,但由于某种原因,我不断遇到指南中未提及的错误。
\n事件控制器测试.cs
\nnamespace UnitTests.ProjectToBeTested.Controllers\n{\n public class EventControllerTests\n {\n [Fact]\n public async Task EventController_Post_RespondsOkIfRequestContainsCorrectFeilds_SuccessAsync()\n {\n\n // Arrange\n var application = new WebApplicationFactory<Program>();\n\n var client = application.CreateClient();\n ...\nRun Code Online (Sandbox Code Playgroud)\n待测试项目.csproj
\n...\n <ItemGroup>\n <InternalsVisibleTo Include="IntegrationTests" />\n </ItemGroup>\n...\nRun Code Online (Sandbox Code Playgroud)\n运行测试时会抛出以下错误:
\n\n\n消息:\xe2\x80\x89 System.InvalidOperationException:在\n\ 上找不到方法“public static\nIHostBuilder CreateHostBuilder(string[] args)\”或“public static\nIWebHostBuilder CreateWebHostBuilder(string[] args)\” '程序\'。或者,可以扩展 WebApplicationFactory`1,并可以重写\n\n\'CreateHostBuilder\' 或 \'CreateWebHostBuilder\' 以提供你自己的实例。
\n堆栈跟踪:\xe2\x80\x89 WebApplicationFactory
\n1.CreateWebHostBuilder() WebApplicationFactory1.EnsureServer()\nWebApplicationFactory1.CreateDefaultClient(DelegatingHandler[] handlers) WebApplicationFactory1.CreateDefaultClient(Uri baseAddress,\nDelegatingHandler[] 处理程序)\nWebApplicationFactory1.CreateClient(WebApplicationFactoryClientOptions options) WebApplicationFactory1.CreateClient()\nEventControllerTests.EventController_Post_RespondsOkIfRequestContainsCorrectFeilds_SuccessAsync()\xe2\x80\x89线\ xe2\x80\x8917\n--- 前一个位置的堆栈跟踪结束 ---
这篇 SO 文章显示为一个可能的解决方案,但使用的是 Startup 类的 pre-6。.NET 6 解决方案是什么?
\n如果我遵循“使用默认 WebApplicationFactory 的基本测试”指南,我什至无法构建解决方案,因为测试类构造函数抛出
\n\n\n错误 CS0051 可访问性不一致:参数类型\n\'WebApplicationFactory\' 的访问性比方法\n\'EventControllerTests.EventControllerTests(WebApplicationFactory)\' IntegrationTests\nC:\\...\\EventControllerTests.cs 更难访问
\n
r .*_* .r 11
解决方案:
这是由于测试项目的 Microsoft.AspNetCore.Mvc.Testing 包使用了错误的版本(它使用的是版本 5.*)。确保您使用适合 .NET 6 的版本。到目前为止,有一个适合我的 6.0.0-rc.2.21480.10 版本。
| 归档时间: |
|
| 查看次数: |
6728 次 |
| 最近记录: |