I am creating Xunit tests, with in-memory database. The tests execute correctly if run separately. However if run in parallel, they collide due to primary key issue in dbcontext.
What is best option to resolve this?
- Does Xunit have teardown capability? Heard xunit does not support this.
- Should I just run tests sequentially?
- Should go ahead and use different key Ids?
Trying to research xunit documentation, just started learning .net programming.
Error:
"System.ArgumentException : An item with the same key has already been added. Key: 2"
Code:
2 is primary key, used twice
public class ProductAppServiceTest
{
public TestContext context;
public IMapper mapper;
public ProductAppServiceTest()
{
var options = new DbContextOptionsBuilder<TestContext>()
.UseInMemoryDatabase(databaseName: "TestDatabase")
.Options;
context = new TestContext(options);
ApplicationServicesMappingProfile applicationServicesMappingProfile = new ApplicationServicesMappingProfile();
var config = new MapperConfiguration(cfg =>
{
cfg.AddProfile(applicationServicesMappingProfile);
});
mapper = config.CreateMapper();
}
[Fact]
public async Task Get_ProductById_Are_Equal()
{
context.Product.Add(new Product { ProductId = 2, ProductCode = "123", ProductName = "ABC" });
context.SaveChanges();
var ProductRepository = new ProductRepository(context);
var ProductAppService = new ProductAppService(ProductRepository, mapper);
var ProductDto = await ProductAppService.GetProductById(2);
Assert.Equal("123", ProductDto.ProductCode);
}
[Fact]
public async Task Get_ProductPrice_Are_Equal()
{
context.Product.Add(new Product { ProductId = 2, ProductCode = "123", ProductName = "ABC" });
context.SaveChanges();
var ProductRepository = new ProductRepository(context);
var ProductAppService = new ProductAppService(ProductRepository, mapper);
var ProductDto = await ProductAppService.GetProductById(2);
//Goes into Enum table to validate price is 5
Assert.Equal("5", ProductDto.Price);
}
databaseName: "TestDatabase"
, have you tried settingdatabaseName: $"{Guid.NewGuid()}"
so each of your parallel runs will use a different DB for the test? Using the same in-memory database might be why they're stepping on each other. – Mra