Unit test uses shared database

Ocelot013 1 Reputation point
2022-05-16T13:05:37.023+00:00

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.
    }
.NET
.NET
Microsoft Technologies based on the .NET software framework.
3,367 questions
ASP.NET Core
ASP.NET Core
A set of technologies in the .NET Framework for building web applications and XML web services.
4,157 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Bruce (SqlWork.com) 55,601 Reputation points
    2022-05-16T19:58:44.943+00:00

    your tests need to roll back any data changes they make.

    you can one of the following:

    • recreate the database before each test
    • truncate all tables before each test
    • begin a transaction and rollback rather than commit with each test
    • write the tests to not assume an empty database.
    • each test undos what it did