[ASP.NET Core 3] 利用 TestServer 進行 Web API 整合測試

 .NET Framework 可以利用 OWIN 把 Web API 掛載起來,用測試打進去,在 .NET Core 可以用 WebHost,如果你需要 .NET Framework 的請到以下連結https://dotblogs.com.tw/yc421206/2019/01/05/webapi_test_via_owin

 

開發環境

  • VS 2019
  • ASP .NET Core 3

TestServer from Nuget

Install-Package Microsoft.AspNetCore.TestHost

 

@ApiTestServer.cs

這裡目前是用 IWebHostBuilder,不知道會不會改成 IHostBuilder

public class ApiTestServer : TestServer
{
    public ApiTestServer() : base(WebHostBuilder())
    {
        this.BaseAddress = new Uri("http://localhost:9527");
    }
 
    private static IWebHostBuilder WebHostBuilder() =>
        WebHost.CreateDefaultBuilder()
               .UseStartup<Startup>();
}

 

@ UnitTest1.cs

在測試專案第一次建立的時候初始化 TestServer、HttpClient

[TestClass]
public class UnitTest1
{
    private static ApiTestServer TestServer;
    private static HttpClient HttpClient;
 
    [AssemblyInitialize]
    public static void AssemblyInitialize(TestContext context)
    {
        TestServer = new ApiTestServer();
        HttpClient = TestServer.CreateClient();
    }
    [AssemblyCleanup]
    public static void AssemblyCleanup()
    {
        TestServer?.Dispose();
        HttpClient?.Dispose();
    }
}

 

在測試方法就可以直接打 Web API,這裡打的是範本內建的 Controller

[TestMethod]
public void TestMethod1()
{
    var url      = "/weatherforecast";
    var response = HttpClient.GetAsync(url).Result;
    Assert.AreEqual(true, response.StatusCode == HttpStatusCode.OK);
}

 

Controller 是範本內建的

[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
{
    private static readonly string[] Summaries = new[]
    {
        "Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"
    };
 
    private readonly ILogger<WeatherForecastController> _logger;
 
    public WeatherForecastController(ILogger<WeatherForecastController> logger)
    {
        _logger = logger;
    }
 
    [HttpGet]
    public IEnumerable<WeatherForecast> Get()
    {
        var rng = new Random();
        return Enumerable.Range(1, 5).Select(index => new WeatherForecast
        {
            Date = DateTime.Now.AddDays(index),
            TemperatureC = rng.Next(-20, 55),
            Summary = Summaries[rng.Next(Summaries.Length)]
        })
        .ToArray();
    }
}

 

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


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

Image result for microsoft+mvp+logo