vendredi 1 juillet 2016

Integration Testing with Entity Framework

We are using EF 6.0 and are trying to figure out how best to simulate a physical database with a mocked in memory database. We have attempted using the Moq approach in the article Mocking EF 6.0 and higher

However, this does not support something like the following:

var person = dbCtx.Persons.Include(x => x.Pets).Where(x => x.ID = 1).Single();
person.Pets.Add(new Pet{ Name = "Spike", Type = "Dog" });
dbCtx.Save();

The problems with the above are as follows:

  1. Mocking the EF Context supports native IEnumerable Linq statements. Include is not part of this set. You can make include work by serializing all values on the root entity, but this doesn't adequately simulate a real world situation. In a real database with LazyLoading turned off, if you did not specify an include then the navigation property of Pets would be null. This is important.
  2. Due to the issue in #1, the IDbSet Pets never gets the newly added pet added to it as the Pet "Spike" is only added to the Person entity that was retrieved. So in post state checking you are unable to check the pets collection to ensure the correct values were entered or updated.

Any insight here would be greatly appreciated.

Aucun commentaire:

Enregistrer un commentaire