Mocking EF core computed field in InMemoryDatabase for unit tests

Viewed 163

In my database I have computed field "FullName" created by EF core using HasComputedColumnSql fluent API and everything is working fine in the app.

However I have some unit tests using InMemory database which are testing some logic using "FullName" column which is null in InMemory database.

Any idea how I can mock computed column behavior in in memory database?

1 Answers

I’m using the following solution:

  1. Add even handler for SavingChanges
  2. Inside the handler, loop over entities of the type ou have a computed column on
  3. Initialize computed value

Example: Add event handler:

dbContext.SavingChanges += OnSaveChanges;

In my case, the class name is Ressource end computed property is “FullName” :

private void OnSaveChanges(object? sender, SavingChangesEventArgs e)
{
    var dbContext = sender as <your context class>;
    var ressources = dbContext.ChangeTracker.Entries().Where(x => x.Entity is Ressource).Select(x => x.Entity as Ressource).ToList();
    foreach (var item in ressources)
        item.FullName = item.FirstName + " " + item.LastName;
}

Hope it helps.

Related