-
Notifications
You must be signed in to change notification settings - Fork 56
Seed from Production Seed database
Jon P Smith edited this page Apr 22, 2019
·
3 revisions
Having run the extract stage you will have a JSON file with the identifying string you provided in the extract stage (typically the database name, but can be just string). In the "seed" stage you read back that data and write it to the unit test database. Here is an example taken from the unit test class TestDataResetter.ExampleSetupAndSeed.
[Fact]
public void ExampleSeedDatabase()
{
//SETUP
var options = SqliteInMemory.CreateOptions<BookContext>();
using (var context = new BookContext(options))
{
//2a. make sure you have an empty database
context.Database.EnsureCreated();
//2b. read the entities back from the JSON file
var entities = "ExampleDatabase".ReadSeedDataFromJsonFile<List<Book>>();
//2c. Optionally “tweak” any specific data in the classes that your unit test needs
entities.First().Title = "new title";
//2d. Add the data to the database and save
context.AddRange(entities);
context.SaveChanges();
//ATTEMPT
//... run your tests here
//VERIFY
//... place your asserts here
}
}
If you have add a large number of entities/rows (say >1,000) then you may find the SaveChanges
method is a bit slow. One thing you can do is remove this running of the ChangeTracker because the Add/AddRange method will set its state for you. You do this by setting the ChangeTracker.AutoDetectChangesEnabled to false when calling SaveChanges to seed the database.
- Testing against a PostgreSQL db
- Changes in EfCore.TestSupport 5
- Testing with production data
- Using an in-memory database (old)