我有下一个测试类,其中包含一个调用简单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"
  -----------^

推荐答案

通过将Guid.NewGuid().ToString()ConfigureTestServicesWithWebHostBuilder中移出来固定数据库名称.此外,我强烈建议也将种子移出,因为不鼓励多次使用服务Provider ,并且可能导致不必要的副作用:

 public void Setup()
 {
      var databaseName = Guid.NewGuid().ToString();
     _factory = new WebApplicationFactory<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(databaseName);
             });
         });
     });
    
     using var scope =  _factory.Services.CreateScope();;
     var db = scope.ServiceProvider.GetService<ApplicationDbContext>();

     SeedData(db);
     _client = _factory.CreateClient();
 }

您当前的代码:

using var scope = services.BuildServiceProvider().CreateScope();

构建一个单独的DI容器,它将拥有自己的一组服务,这些服务不会与测试服务器使用的服务相关(这将启动它自己的容器).

Csharp相关问答推荐

更改对象的旋转方向

为什么我的ASP.NET核心MVC应用程序要为HTML元素添加一些标识符?

NumPy s fftn in C#with pythonnet'

MudBlazor—MudDataGrid—默认过滤器定义不允许用户修改基本过滤器

.NET 8 Web-API返回空列表

有没有办法在WPF文本框中添加复制事件的处理程序?

.NET 6控制台应用程序,RabbitMQ消费不工作时,它的程序文件中的S

内部接口和类的DI解析

从ASP.NET Core中的枚举字段填充 Select 选项时,将默认的第一个选项添加为 Select 元素

调用Task.Run()与DoSomethingAsync()有什么不同?

我如何让我的秒表保持运行场景而不重置

将C#类导入到PowerShell

为什么在使用JsonDerivedType序列化泛型时缺少$type?

FakeItEasy自动嘲弄内容

为什么当我try 为玩家角色设置动画时,没有从文件夹中拉出正确的图像?

为什么我可以在注册表编辑器中更改值,但不能在以管理员身份运行的C#表单应用程序中更改?

Autofac -动态实例化:手动传递构造函数

在C#中通过Matheval使用自定义公式

如果所有";async任务方法()";调用都返回Task.FromResult()-是否同步执行?

Windows 10上埃及标准时间的时区偏移不正确