我有下一个测试类,其中包含一个调用简单API端点的集成测试.
在设置方法中,我将实际数据库替换为InMemory,并try 将有关两个城市的信息添加到数据库中.
public class TestControllerTest
{
private WebApplicationFactory<RentAPI.Program> _factory;
private HttpClient _client;
[SetUp]
public void Setup()
{
_factory = new WebApplicationFactory<RentAPI.Program>().WithWebHostBuilder(builder =>
{
builder.ConfigureTestServices(services =>
{
var dbContextDescriptor = services.SingleOrDefault(d =>
d.ServiceType == typeof(DbContextOptions<ApplicationDbContext>));
services.Remove(dbContextDescriptor);
services.AddDbContext<ApplicationDbContext>(options =>
{
options.UseInMemoryDatabase(Guid.NewGuid().ToString());
});
using var scope = services.BuildServiceProvider().CreateScope();
var db = scope.ServiceProvider.GetService<ApplicationDbContext>();
SeedData(db);
});
});
_client = _factory.CreateClient();
}
[Test]
public async Task Test_test()
{
var response = await _client.GetAsync("/Test");
var stingResult = await response.Content.ReadAsStringAsync();
Assert.That(stingResult, Is.EqualTo("3"));
}
[TearDown]
public void TearDown()
{
_client.Dispose();
_factory.Dispose();
}
public static void SeedData(ApplicationDbContext context)
{
context.Cities.AddRange(
new City { Id = 1, Name = "City1" },
new City { Id = 2, Name = "City2" }
);
context.SaveChanges();
}
}
这是终点
[ApiController, Route("[controller]")]
public class TestController : ControllerBase
{
private readonly IUnitOfWork _uow;
public TestController(IUnitOfWork uow) => _uow = uow;
[HttpGet]
public async Task<ActionResult<string>> Test()
{
await _uow.CityRepository.AddAsync(new City() { Id = 99, Name = "Poko" });
await _uow.CompleteAsync();
var cities = await _uow.CityRepository.FindAllAsync();
return cities.Count().ToString();
}
}
问题是,尽管我try 将城市信息添加到我的应用程序使用的数据库中,但当我在测试中调用Endpoint时,这些记录不会出现.
以下是测试结果:
String lengths are both 1. Strings differ at index 0.
Expected: "3"
But was: "1"
-----------^