WebApplicationFactory
は、テスト環境でアプリケーションを起動し、エンドポイントをテストできる便利なツール、WebApplicationFactory
を使用したテストの実装方法。
Microsoft.AspNetCore.Mvc.Testing
パッケージをインストール
Install-Package Microsoft.AspNetCore.Mvc.Testing
シンプルなAPI(VSでの初期実装)
using Microsoft.AspNetCore.Mvc;
namespace SampleApi.Controllers
{
[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(Name = "GetWeatherForecast")]
public IEnumerable<WeatherForecast> Get()
{
return Enumerable.Range(1, 5).Select(index => new WeatherForecast
{
Date = DateTime.Now.AddDays(index),
TemperatureC = Random.Shared.Next(-20, 55),
Summary = Summaries[Random.Shared.Next(Summaries.Length)]
})
.ToArray();
}
}
}
WebApplicationFactory
を使用して、WeatherForecastController
のエンドポイントをテスト。テストプロジェクト内でWebApplicationFactory
を使ってエンドポイントをテストする。
using System.Net.Http;
using System.Threading.Tasks;
using Xunit;
using Microsoft.AspNetCore.Mvc.Testing;
using MyApp;
public class SampleTests : IClassFixture<WebApplicationFactory<Startup>>
{
private readonly HttpClient _client;
public SampleTests(WebApplicationFactory<Startup> factory)
{
_client = factory.CreateClient();
}
[Fact]
public async Task Get_ReturnsList()
{
// Arrange
var request = "/WeatherForecast/GetWeatherForecast";
// Act
var response = await _client.GetAsync(request);
// Assert
response.EnsureSuccessStatusCode();
var content = await response.Content.ReadAsStringAsync();
Assert.Contains("Summary", content);
}
}