In Entity Framework you can configure the relationship between your entities by either using data annotations inside the actual class entity:
public class Entity
{
[Key, Column(Order = 0)]
public Guid PartOfPrimaryKey { get; set; }
[Key, Column(Order = 1)]
public Guid AlsoPartOfPrimaryKey { get; set; }
}
or by using the fluent API configuration
modelBuilder.Entity<Entity>()
.HasKey(k => new { k.PartOfPrimaryKey, k.AlsoPartOfPrimaryKey });
Give that you've used the fluent API configruation approach, how do you make sure the configuration is executed while mocking (using Moq) the DbContext for unit testing?
When i mock the DbContext
the method OnModelCreating
is not being executed.
Here is an explanation of how to test your application using a mocking framwork, but it doesn't explain how they take care of the problem with "configuring" the entities. Other posts I have found doesn't address this issue either. I guess there's something simple i'm missing.
Sidenote: I'm also aware of that it might not be a good idea at all to unit test your DbContext because you will use LINQ to Objects in your tests and LINQ to entites in production. However, I still think there is an answer to my question.
Update: If I use the data annotations instead, it works fine.