How to correctly test the Data access layer using Mock , namely repositories that provide access to the database through the context?

The problem is that each repository receives a DbContext as an argument. This context returns a Ninject .

 public UserRepository(DbContext context) 

I wanted to slip a fake DbContext , but I can't create a DbSet object

 Mock<DbContext> context = new Mock<DbContext>(); context.Setup(c => c.Set<User>()).Returns( ??? ); 
  • I would recommend you read about Google's unit testing framework . - user232857
  • Google’s @AndreyYanov C ++ test framework is for C ++. What does it have to do with the DBContext mocking in C #? - PashaPash
  • @PashaPash looked-watched and could not understand how to use it under C #. It originated the same as you. - Vadim Prokopchuk

1 answer 1

An analysis of the situation showed only two ways out of the situation:

  1. Creating a database for testing and conducting all manipulations on it. This approach is almost immediately thrown back for personal reasons - the tests are dependent on each other.
  2. Creating a wrapper on the context and further use through the wrapper interface:

     interface IDbRepository { DbContext Context { get; } IQueryable<MyType> MyTypes { get; } // etc. } 

And the wrapper itself

 public class DbRepository : IDbRepository { DbContext context; public DbRepository(DbContext context) { this.context = context; } public DbContext Context { get { return context; } } public IQueryable<MyType> MyTypes { get { return context.Set<MyType>(); } } 

We replace the old context with the interface

public UserRepository (DbContext context)

 public UserRepository(IDbRepository repository) 

And now you can test the UserRepository using Mock

 Mock<IDbRepository> wrapper = new Mock<IDbRepository>(); wrapper.Setup(c => c.MyTypes).Returns( new [] { new MyType(...) }.AsQueryable() ); 

I doubt the correctness. Repositories are now less flexible.