【发布时间】:2019-11-15 12:53:05
【问题描述】:
我创建了一个 XUnit 夹具来定义 EF Core 上下文初始数据:
public class ServiceProviderFixture : IDisposable {
public IServiceProvider Provider { get; private set; }
public ServiceProviderFixture() {
IServiceCollection services = new ServiceCollection();
services.AddDbContext<Context>(x => { x.UseInMemoryDatabase("Database"); });
Provider = services.BuildServiceProvider();
BuildContext();
}
private void BuildContext() {
Context context = Provider.GetService<Context>();
context.Countries.Add(new Country { Code = "fr", Name = "France" });
context.SaveChanges();
}
public void Dispose() { }
}
然后在一些测试中我使用它如下:
public class TestMethod1 : IClassFixture<ServiceProviderFixture> {
public Test(ServiceProviderFixture fixture) {
_fixture = fixture;
}
[Fact]
public async Task Test1() {
IServiceProvider provider = _fixture.Provider;
Context context = provider.GetService<Context>();
// Add test data to context
// Test some method
}
}
当我运行一项测试时,它运行良好......但是当我使用 dotnet test 运行所有测试时,我得到:
An item with the same key has already been added. Key: fr
The following constructor parameters did not have matching fixture data:
ServiceProviderFixture fixture)
我相信 BuildContext() 在同一上下文中的每个 TestClass 都会被调用一次。
我该如何解决这个问题?
【问题讨论】:
标签: c# asp.net-core entity-framework-core xunit xunit.net