播种WebApplicationFactory进行集成测试不会保存并给出404

时间:2020-02-06 20:02:14

标签: c# asp.net testing .net-core integration-testing

因此,我试图使用dbcontext中的预置数据创建一个集成测试,但是由于某种原因,它没有将我的条目保存到数据库中,并且在我返回响应后找不到404。如有需要,很乐意扩展或澄清任何内容。

欢呼

[Fact]
public async Task GetPet_ReturnsResourceWithAccurateFields()
{
    var fakePet = new FakePet { }.Generate();
    fakePet.PetId = 1;

    var appFactory = new WebApplicationFactory<StartupAutomatedTesting>()
        .WithWebHostBuilder(builder =>
        {
            builder
                .ConfigureServices(services =>
                {
                    services.Remove(new ServiceDescriptor(typeof(MyDbContext),
                        typeof(MyDbContext)));
                    services.AddDbContext<MyDbContext>(options =>
                    {
                        options.UseInMemoryDatabase("TestDb");
                    });

                    var serviceProvider = services
                        .AddEntityFrameworkInMemoryDatabase()
                        .BuildServiceProvider();

                    using (var scope = serviceProvider.CreateScope())
                    {
                        var context = scope.ServiceProvider.GetRequiredService<MyDbContext>();
                        context.Database.EnsureCreated();

                        context.Pets.AddRange(fakePet);
                        context.SaveChanges();
                    }
                });
        });

    var testingClient = appFactory.CreateClient();


    var result = await testingClient.GetAsync($"/v1/Pets/{fakePet.PetId}");
    var responseContent = await result.Content.ReadAsStringAsync();
    var response = JsonConvert.DeserializeObject<PetDto>(responseContent);

    // Assert
    response.Name.Should().Be(fakePet.Name);
    response.Age.Should().Be(fakePet.Age);
}

1 个答案:

答案 0 :(得分:0)

可能是由于您创建的(中间)服务提供者获取了自己的内存数据库单例实例。

在创建appFactory之后移动种子部分,并从appFactory解析服务提供者的dbcontext:

var appFactory = new WebApplicationFactory<StartupAutomatedTesting>()
   .WithWebHostBuilder(builder =>
   {
       ... etc ...
   });

using (var scope = appFactory.Services.CreateScope())
{
    var context = scope.ServiceProvider.GetRequiredService<MyDbContext>();
    context.Database.EnsureCreated();

    context.Pets.AddRange(fakePet);
    context.SaveChanges();
}

var testingClient = appFactory.CreateClient();

... etc ...