選單
GSS 技術部落格
在這個園地裡我們將從技術、專案管理、客戶對談面和大家分享我們多年的經驗,希望大家不管是喜歡或是有意見,都可以回饋給我們,讓我們有機會和大家對話並一起成長!
若有任何問題請來信:gss_crm@gss.com.tw
3 分鐘閱讀時間 (651 個字)

如何使用 test host 對.net core web api 進行整合測試

如何使用 test host 對.net core web api 進行整合測試

 前言

  對於 Web API 的測試時,常常使用 Postman、Fiddler、Newman... 等工具進行測試,但是如果 Web API 和其他的服務 (如:Web API、資料庫) 耦合很高時,要完成這個測試勢必需要將相依的服務執行起來。因此本篇主要是要介紹如何在本機透過 Microsoft.AspNetCore.TestHost 對 Web API 進行測試。

 環境 & NuGet 套件

  • 環境

    • .NET Core
  • 單元測試專案 (任選一種)

    • MSTest
    • Xunit (本篇範例選擇的測試套件)
    • Nunit
  • NET Core Web API 測試套件

    • Microsoft.AspNetCore.TestHost

      • 安裝 .NET Core 對應的版本號,例如:.NET Core 3.1 專案就安裝 3.1.x 版
  • Mock 測試套件 (可選)

    • Moq

實作 .NET Core Web API 整合測試

(1) 建立測試專案、測試類別

宣告 TestServer、HttpClient、Configuration 三個物件

using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.TestHost;
using Microsoft.Extensions.Configuration;
using Xunit;

public class DemoControllerTest
{
    // Test Web API Host
    private readonly TestServer Server;
    
    // 主要用來呼叫 TestServer 時使用
    private readonly HttpClient Client;

    // 提供 Web API 使用的組態設定,可使用測試用組態設定
    private readonly IConfiguration Configuration;
} 

 (2) 在 Setup 建立 Test Server 和 Http Client

  1. 建立 Setup

    • XUnit 的 Setup 就是 Constructor
    • MSTest 是加上 [TestInitialize] Attribute
    • Nunit 是加上 [SetUp] Attribute
  2. 設定 Configuration

    • 可以透過設定 Configuration 來指定測試資料庫 或 相關服務
  3. 建立 WebHostBuilder,設定執行環境、Configutation 和測試目標 (Web API 專案) 的 Startup 類別

  4. 設定 TestServer,Test Web API Host

  5. 設定 HttpClient,主要用來呼叫 TestServer 時使用的

  6. 最後,也可以在 Setup 和 Teardown 分別加入測試資料的準備和復原

    • 例如:資料庫的操作
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.TestHost;
using Microsoft.Extensions.Configuration;
using Xunit;

public class DemoControllerTest
{
    private readonly TestServer Server;
    private readonly HttpClient Client;
    private readonly IConfiguration Configuration;
    
    public DemoControllerTest()
    {
        // 讀取 appsettings.json
        Configuration = new ConfigurationBuilder().AddJsonFile("appsettings.json",
                                                               optional: true,
                                                               reloadOnChange: true)
                                                  .Build();

        // 設定 Web Host,執行環境、Configutation、Web API 的 Startup 類別
        var builder = new WebHostBuilder().UseEnvironment("Test")
                                          .UseConfiguration(Configuration)
                                          .UseStartup<Startup>();

        // 建立 Test Server 和 Http Client
        Server = new TestServer(builder);
        Client = Server.CreateClient();
    }
} 

(3) 實作測試案例 

  • 透過前面建立 Http Client 呼叫要測試的 Web API (Test Server)
  • 驗證返回的 Response
[Fact]
public async Task TestGetVersion()
{
    // Arrange 
    string url = "api/version";
	string exceptionVersion = Configuration.GetSection("Version").Value.ToString();

    // Act
    HttpResponseMessage response = await Client.GetAsync(url);
    string responseRaw = await response.Content.ReadAsStringAsync();

    // Assert
    Assert.True(response.IsSuccessStatusCode);
    Assert.Equal(exceptionVersion, responseRaw);
} 

如何替換掉透過 Dependency Injection 注入的 Service

測試時可能會因為使用到一些從 Dependency Injection 注入的 Service,導致測試難以進行

  • 在 SetUp 時,透過 ConfigureTestServices 替換掉相關的 Services

    • 透過替換成 Test Service 讓測試能夠順利進行
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.TestHost;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Xunit;

public class DemoControllerTest
{
    private readonly TestServer Server;
    private readonly HttpClient Client;
    private readonly IConfiguration Configuration;
    
    public DemoControllerTest()
    {
        // 讀取 appsettings.json
        Configuration = new ConfigurationBuilder().AddJsonFile("appsettings.json",
                                                               optional: true,
                                                               reloadOnChange: true)
                                                  .Build();

        // 設定 Web Host,執行環境、Configutation、Web API 的 Startup 類別
        var builder = new WebHostBuilder().UseEnvironment("Test")
                                          .UseConfiguration(Configuration)
                                          .UseStartup<Startup>();
                                          
        // 替換掉相關的 Service,讓測試能夠順利進行
        builder.ConfigureTestServices((services) =>
        {
            services.AddSingleton<IMyService>(new MyMockService());
        });

        // 建立 Test Server 和 Http Client
        Server = new TestServer(builder);
        Client = Server.CreateClient();
    }
} 

可以搭配 Moq 替換掉相關的 Service

// 建立 Mock Service
Mock<IMyService> testService = new Mock<IMyService>(MockBehavior.Strict);
testService.Setup(g => g.GetResult())
           .Returns("my-mock-result");

// 替換掉相關的 Service,讓測試能夠順利進行
builder.ConfigureTestServices((services) =>
{
    services.AddSingleton<IMyService>(testService.Object);
}); 
心靈成長-"拖延心理學"摘要分享 #前篇
dotnet部署至iis server

相關文章

 

評論

尚無評論
已經注冊了? 這裡登入
Guest
2025/04/27, 週日

Captcha 圖像