Mocking DbContext with smooth API configuration

In the Entity Framework, you can configure the relationship between your objects using data annotations inside the actual class object:

public class Entity { [Key, Column(Order = 0)] public Guid PartOfPrimaryKey { get; set; } [Key, Column(Order = 1)] public Guid AlsoPartOfPrimaryKey { get; set; } } 

or using the free API configuration

  modelBuilder.Entity<Entity>() .HasKey(k => new { k.PartOfPrimaryKey, k.AlsoPartOfPrimaryKey }); 

Make it clear that you took a simple approach to setting up the API, how do you make sure that the configuration is done by mocking (using Moq) DbContext for unit testing?

When I cheat on DbContext , the OnModelCreating method OnModelCreating .

It explains how to test your application using a mocking framework, but it doesn’t explain how they care about the problem of "setting up" objects. Other posts I found also do not address this issue. I guess something simple is missing me.

Sidenote: I also know that this may not be a good idea for the unit test of your DbContext, because you will use LINQ for objects in your tests and LINQ for production . However, I still think there is an answer to my question.

Update: if I use data annotations instead, it works fine.

+5
source share
2 answers

I would never scoff at ORM. I prefer to create intermediate classes that implement the interface (such as the repository) and the layout of this interface. However, let's see what I can do for you:

A good way to mock DbContext for unit testing, which will work with the Fluent API, annotations, etc., is to use the built-in database. Even if this database is still fast enough for unit testing. It also allows you to transparently evaluate the insert or insert-update-read reading sequence.

Please see this Q & A (and do not accept the accepted answer as the best, because it is not):

Is there an Entity Framework provider in my memory?

+1
source

At first, I also used Moq to test the code on the database. But after a while I had problems, and nothing worked out as expected.

Now I use it here: http://effort.codeplex.com/

Take a look at this. For me it is much easier to check my code. And much faster to write tests for him.

0
source

Source: https://habr.com/ru/post/1200762/


All Articles