如何使用WebApplicationFactory播种测试数据?

时间:2020-06-07 15:10:08

标签: c# testing .net-core integration-testing ef-core-3.1

我正在为.NET Core 3.1 Web API进行集成测试。我关注了这篇文章Painless Integration Testing with ASP.NET Core Web API。这是我的CustomWebApplicationFactory

public class CustomWebApplicationFactory<TStartup> : WebApplicationFactory<TStartup> where TStartup : class
{
    protected override void ConfigureWebHost(IWebHostBuilder builder)
    {
        builder.ConfigureServices(services =>
        {
            var descriptor = services.SingleOrDefault(d => d.ServiceType == typeof(DbContextOptions<TestDbContext>));
            if (descriptor != null)
            {
                services.Remove(descriptor);
            }

            services.AddDbContext<TestDbContext>(options =>
            {
                options.UseInMemoryDatabase("InMemoryTestDb");
            });

            var sp = services.BuildServiceProvider();

            using (var scope = sp.CreateScope())
            {
                var scopedServices = scope.ServiceProvider;
                var db = scopedServices.GetRequiredService<TestDbContext>();
                var logger = scopedServices.GetRequiredService<ILogger<CustomWebApplicationFactory<TStartup>>>();

                db.Database.EnsureCreated();

                try
                {
                    Console.WriteLine("Seeding...");

                    var players = Utilities.GetTestPlayers(); // Returns 3 test players
                    db.Players.RemoveRange(db.Players); // Clear the table
                    db.Players.AddRange(players); // Add 3 test players
                    db.SaveChanges();

                    Console.WriteLine($"Players seeded: { db.Players.Count() }");
                }
                catch (Exception ex)
                {
                    logger.LogError(ex, "An error occurred seeding the " + "database with test messages. Error: {Message}", ex.Message);
                }
            }
        });
    }
}

以下是我的测试:我为每个Controller在单独的类中创建了测试。在测试类的构造函数中,我创建一个Client。对于TestController,就像这样(API中总共有4个Controller):

public class BaseControllerTest : IClassFixture<CustomWebApplicationFactory<Startup>>
{
    protected HttpClient Client { get; }

    public BaseControllerTest(CustomWebApplicationFactory<Startup> factory)
    {
        Client = factory.CreateClient();
    }
}

public class TestControllerShould : BaseControllerTest
{
    public TestControllerShould(CustomWebApplicationFactory<Startup> factory)
        : base(factory)
    {
        Console.WriteLine("TestControllerShould");
    }

    [Fact]
    public async Task GetHelloWorld()
    {
        var request = new HttpRequestMessage(new HttpMethod("GET"), "/test/");
        var response = await Client.SendAsync(request);

        Assert.Equal(HttpStatusCode.OK, response.StatusCode);
        var content = await response.Content.ReadAsStringAsync();
        Assert.Equal("Hello World!", content);
        Assert.False(response.Headers.Contains("Server"), "Should not contain server header");
    }
} 

我的问题是:

正如您在CustomWebApplicationFactory中看到的那样,我在播种时正在记录日志,这是我看到的日志:

Seeding...
Seeding...
Seeding...
Seeding...
Players seeded: 12
Players seeded: 12
Players seeded: 12
Players seeded: 12

我总共有4个控制器,而我只播种了3个玩家。为什么我看到12?我不明白看来db.Players.AddRange(players);行在任何db.SaveChanges();之前被调用了4次(对于每个Controller测试类)。然后db.SaveChanges();被连续调用4次。为什么?

我的问题是:为什么?以及如何在集成测试中正确植入测试数据?

(如果不是通过回答,则将不胜感激

谢谢

1 个答案:

答案 0 :(得分:1)

它为每个控制器调用ConfigureServices。 所以在这里你可以做一件事 在致电db.Database.EnsureCreated()之前,请致电db.Database.EnsureDeleted()。 它将为每个控制器重新初始化内存数据库。