ASP.NET Core 6 Top-level Statements 如何使用 WebApplicationFactory 進行整合測試

C# 9 開始就可以不用在主控台程式包含 main 方法(Top-level statements),在 .NET 6,ASP.NET Core 6 也支援了 Top-level statements 專案範本,已經直接套用此功能,我用 WebApplicationFactory 寫整合測試時,碰到一點小問題,以下是解決問題的經過

開發環境

  • ASP.NET Core 6
  • Rider 2022.1.1

問題描述

TestServer 實作了 WebApplicationFactory<Program>

public class TestServer : WebApplicationFactory<Program>
{
    private void ConfigureServices(IServiceCollection services)
    {

    }

    protected override void ConfigureWebHost(IWebHostBuilder builder)
    {
        builder.ConfigureServices(this.ConfigureServices);
    }
}

詳細作法可以參考上篇:
[ASP.NET Core 5] 利用 WebApplicationFactory 進行 Web API 整合測試 | 余小章 @ 大內殿堂 - 點部落 (dotblogs.com.tw)

在測試程式碼調用 TestServer 

[TestMethod]
public void TestMethod1()
{
    var server = new TestServer();
    var httpClient = server.CreateClient();
    var url = "demo";
    var response = httpClient.GetAsync(url).Result;
    var result = response.Content.ReadAsStringAsync().Result;
    Console.WriteLine(result);
}

 

出現例外

System.InvalidOperationException: Can't find 'D:\src\sample.dotblog\WebAPI\Security\Lab.AspNetCore.Security\Lab.AspNetCore.Security.BasicAuthenticationSite.IntegrateTest\bin\Debug\net6.0\testhost.deps.json'. This file is required for functional tests to run properly. There should be a copy of the file on your source project bin folder. If that is not the case, make sure that the property PreserveCompilationContext is set to true on your project file. E.g '<PreserveCompilationContext>true</PreserveCompilationContext>'. For functional tests to work they need to either run from the build output folder or the testhost.deps.json file from your application's output directory must be copied to the folder where the tests are running on. A common cause for this error is having shadow copying enabled when the tests run.
  at Microsoft.AspNetCore.Mvc.Testing.WebApplicationFactory`1.EnsureDepsFile()
  at Microsoft.AspNetCore.Mvc.Testing.WebApplicationFactory`1.EnsureServer()
  at Microsoft.AspNetCore.Mvc.Testing.WebApplicationFactory`1.CreateDefaultClient(DelegatingHandler[] handlers)
  at Microsoft.AspNetCore.Mvc.Testing.WebApplicationFactory`1.CreateDefaultClient(Uri baseAddress, DelegatingHandler[] handlers)
  at Microsoft.AspNetCore.Mvc.Testing.WebApplicationFactory`1.CreateClient(WebApplicationFactoryClientOptions options)
  at Microsoft.AspNetCore.Mvc.Testing.WebApplicationFactory`1.CreateClient()
  at Lab.AspNetCore.Security.BasicAuthenticationSite.IntegrateTest.UnitTest1.TestMethod1() in D:\src\sample.dotblog\WebAPI\Security\Lab.AspNetCore.Security\Lab.AspNetCore.Security.BasicAuthenticationSite.IntegrateTest\UnitTest1.cs:line 13

 

解決方法

在 Program.cs,加上

public partial class Program { }

 

參考

ASP.NET Core 中的整合測試 | Microsoft Docs

若有謬誤,煩請告知,新手發帖請多包涵


Microsoft MVP Award 2010~2017 C# 第四季
Microsoft MVP Award 2018~2022 .NET

Image result for microsoft+mvp+logo