Mocking DbContext for TDD Repository

孤街醉人 提交于 2019-12-06 19:34:36

You need to mock out the Set<T>() call.

Something like this should work out.

// Arrange
var context = new Mock<Context>();
var set = new Mock<DbSet<User>>();

context.Setup(c => c.Set<User>()).Returns(set.Object);

// Act

// Assert
set.Verify(s => s.Add(It.IsAny<User>()), Times.Once());

You don't really need to make verify anything except that Add() was called on the underlying DbSet. Doing your verify on the fact that the Entity state was modified is unnecessary. If you verify that Add() was called that should be enough as you can safely assume that EF is working properly.

This example only works for repositories for your User object. You would have to setup the mocks differently for each repository you want to test in this way. You could probably write up a more generic version of this if needed.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!