Integration testing the entity framework - separate the seed method call only for PROD -

984 views Asked by At

I want to integration test my repositories.

I want to setup and insert test data before each integration test method. Then I want to execute my repository logic Then I want to assert that the logic works by returning the correct data from the database.

I do not want to mock and unit test the DbSet ;-) just real integration tests.

My question is about the whole setup of the database and clearing the test data.

I use code first approach generating a TestDatabase and ProdDatabase. In the ProdDatabase I seed real data to play then with it in the UI and check the correct behavior. The TestDatabase is just for the integration tests.

Both databases are created from ONE context.

When I change any property of an entity and I run my integration tests then the overwritten Seed method from my DbContext is called too. But I do not want that for my TestDatabase.

How can I separate the Seed call happen only for my ProdDatabase? And my TestDatabase generates its own "seed"/setup data per test?

1

There are 1 answers

5
jjj On BEST ANSWER

In each case, you can set a different IDatabaseInitializer or DbMigrationsConfiguration (if you're using MigrateDatabaseToLatestVersion for your initializer) during application startup:

System.Data.Entity.Database.SetInitializer(new TestOrProdInitializer());

You can even set the database initializer using different configuration file settings for production vs. test:

<contexts> 
  <context type=" Blogging.BlogContext, MyAssembly"> 
    <databaseInitializer type="Blogging.MyCustomBlogInitializer, MyAssembly" /> 
  </context> 
</contexts>

If you need to reseed after dropping the database, you can also force initialization with dbContext.Database.Initialize(true).