简体   繁体   中英

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.

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?

At first I also used Moq to test my code against the database. But after a while I had issues and nothing worked as expected.

Now I am using this one here: http://effort.codeplex.com/

Take a look at it. For me it's much easier to test my code. And it's much faster to write tests for it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM