Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mocking DbContext with fluent API configuration

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.

like image 927
Jim Aho Avatar asked Aug 20 '14 14:08

Jim Aho


1 Answers

I'd never mock an ORM. I prefer to create intermediate classes that implement an interface (for example a repository) and mock that interface. However, let's see what I can do for you:

A good way to mock a DbContext for unit testing that will work with Fluent API, annotations, and so on, is to use an in-memory DB. Even if it's a DB is still fast enough for unit testing. It also allows you to mock an insert-read or insert-update-read sequence in a transparent way.

Please, see this Q&A (and don't take the accepted answer as the best one, because it isn't):

Is there an in-memory provider for Entity Framework?

like image 153
JotaBe Avatar answered Oct 16 '22 06:10

JotaBe