I’m doing a small practice project to improve my unit testing skills. I’m using Entity Framework Code First.
I’m using a FakeDBSet, which works well for simple lists of entities. When entity trees are returned things aren’t so nice. In particular two way relationships aren’t maintained as this is part of the Entity Framework magic.
I have two classes:
public class Book
{
public virtual ICollection<Review> Reviews {get; set;}
}
public class Review
{
public virtual Book Book { get; set;}
}
If I set the book for a review, the review does not get added to the book’s review collection. It does when using EF, but not in my fake version.
Is there a way mock this behaviour, or should I not rely on EF to implement two way relationships? Or is mocking the data context just a waste of time?
This is actually a pretty common problem (and one without a really good answer). There is a process which happens inside of EF called fixups which runs inside the detect changes loop (the one that triggers on add/remove and a few other changes). This evaluates backlinks in your model. When you start mocking your context you are going to lose that detect changes loop and hence the fixups.
In the past I’ve gotten around this by understanding this particular limitation of my mocks and making sure i do my setup code in the correct way to make sense in the code (which lets face it is pretty un-ideal). The other option here is to go to some form of real lightweight database in your unit tests and keep using EF.