.NET
Microsoft Technologies based on the .NET software framework.
3,395 questions
This browser is no longer supported.
Upgrade to Microsoft Edge to take advantage of the latest features, security updates, and technical support.
I've implemented unit tests in my app, when I run my test individually all pass but when I run them individually I get some fail.
here is how I create InMemory db.
public static DbContextOptionsBuilder<T> GetDbContextOptionsBuilder<T>( string? connectionString =null, bool enableLazyLoading = false , Guid? databaseId = null)
where T : DbContext
{
var optionBuilder = new DbContextOptionsBuilder<T>();
if (databaseId is null)
databaseId = Guid.NewGuid();
optionBuilder.UseInMemoryDatabase( $"Pm-api-{databaseId:N}")
.EnableSensitiveDataLogging()
.EnableDetailedErrors();
return optionBuilder;
}
And tests:
[Fact]
public async Task Can_Add_Product()
{
var modelCode = "test";
var option = DbContextInitialization.GetDbContextOptionsBuilder<MyDbContext>().Options;
await using var db = new MyDbContext(option , MediatorHelper.Initialize() );
var category = db.SeedCategory();
// Add product code removed for brevity
var actualProduct = await db.Products.FirstAsync();
actualProduct.ShouldNotBeNull();
actualProduct.ModelCode.Value.ShouldEqual( modelCode );
}
[Fact]
public async Task Can_Save_Add_Product()
{
var option = DbContextInitialization.GetDbContextOptionsBuilder<MyDbContext>().Options;
await using var db = new MyDbContext( option, MediatorHelper.Initialize() );
var category =db.SeedCategory();
var product =db.SeedProduct(category);
db.SeedServiceTypes();
// Add product code removed for brevity
var actualProduct = await db.Products.FirstAsync();
//db.products now have two products, one is added in Can_Add_Product test and one is added with current test, which only one product should be available, if I run these two test indivudually then it passes.
}
your tests need to roll back any data changes they make.
you can one of the following: