在实体框架 6.1 中模拟 DbContext

Mocking DbContext in Entity Framework 6.1(在实体框架 6.1 中模拟 DbContext)
本文介绍了在实体框架 6.1 中模拟 DbContext的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我找到了一些示例,这些示例(显然)显示了使用 EF 6 模拟 DbContext 的一个清晰的工作示例,但是,它们似乎都不适合我,我也不完全确定为什么.

I have found a number of examples that show (apparently) a clear working example of mocking DbContext with EF 6, however, none of them seem to work for me and I am not entirely sure why.

这是我设置模拟的单元测试代码;

This is my unit test code that sets up the mock;

var mockData = new List<User> { new User { Email = "my@email.com", Id = 1 } }.AsQueryable();

var mockSet = new Mock<DbSet<User>>();
    mockSet.As<IQueryable<User>>().Setup(m => m.Provider).Returns(mockData.Provider);
    mockSet.As<IQueryable<User>>().Setup(m => m.Expression).Returns(mockData.Expression);
    mockSet.As<IQueryable<User>>().Setup(m => m.ElementType).Returns(mockData.ElementType);
    mockSet.As<IQueryable<User>>().Setup(m => m.GetEnumerator()).Returns(mockData.GetEnumerator());

    var mockContext = new Mock<MyDbContext>();
    mockContext.Setup(c => c.Users).Returns(mockSet.Object);

然后调用我正在测试的服务;

and then the call to the service I am testing;

var service = new UsersService(mockContext.Object);

var user = service.GetById(1);

这会引发 NullReferenceException,因为基础 DbSet 始终为 null.代码执行以下操作;

This throws a NullReferenceException as the underlying DbSet is always null. The code does the following;

在基类中;

public IEnumerable<T> GetAll()
{
    return _dbSet.AsEnumerable();
}

在子类中;

  public User GetById(int id)
        {
            return GetAll().FirstOrDefault(x => x.Id == id);
        }

请注意,尽管关于 SO 的其他问题似乎相关,但它们不包括 EF 6.

Please note that although there are other questions on SO that appear to be related, they do not cover EF 6.

作为参考,这是一篇 MSDN 文章,对相同的代码进行修改以使其编译.

For reference, this is an MSDN article that the same code with a modification to make it compile.

https://msdn.microsoft.com/en-us/data/dn314429.aspx

降低 UserService 的复杂性(它使用泛型/接口),代码现在很简单;

Reducing the complexity of the UserService (its uses generics/interfaces), the code is now simply;

public User GetById(int id)
        {
            return _dbContext.Set<User>().FirstOrDefault(x => x.Id == id);
        }

如果我将其进一步更改为;

If I change this further to;

   var dbSet = _dbContext.Set<User>();
        return dbSet.FirstOrDefault(x => x.Id == id);

我可以清楚地看到 dbSet 为空.

I can clearly see that dbSet is null.

编辑 2

根据 wablab 的建议,mock .Set 似乎解决了问题.

As per the suggestion from wablab, it appears that mock .Set resolved the problem.

还要感谢 Vladyslav Kushnir 为 DbSet 的通用方法.

Credit also to Vladyslav Kushnir for the Generic method for DbSet.

任何可能需要它的人的工作代码;

Working code for this for anyone that might need it;

 private static Mock<DbSet<T>> GetDbSetMock<T>(IEnumerable<T> items = null) where T : class
        {
            if (items == null)
            {
                items = new T[0];
            }

            var dbSetMock = new Mock<DbSet<T>>();
            var q = dbSetMock.As<IQueryable<T>>();

            q.Setup(x => x.GetEnumerator()).Returns(items.GetEnumerator);

            return dbSetMock;
        }



var mockContext = new Mock<Model1>();

var users = new List<User> { new User { Email = "my@email.com", Id = 1 } };

mockContext.Setup(x => x.Set<User>()).Returns(GetDbSetMock(users).Object);

var service = new UsersService(mockContext.Object);

var user = service.GetById(1);

推荐答案

我认为你需要在 Set<User>() 方法上创建一个设置来返回你的模拟.

I think you need to create a setup on the Set<User>() method to return your mock.

这篇关于在实体框架 6.1 中模拟 DbContext的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

DispatcherQueue null when trying to update Ui property in ViewModel(尝试更新ViewModel中的Ui属性时DispatcherQueue为空)
Drawing over all windows on multiple monitors(在多个监视器上绘制所有窗口)
Programmatically show the desktop(以编程方式显示桌面)
c# Generic Setlt;Tgt; implementation to access objects by type(按类型访问对象的C#泛型集实现)
InvalidOperationException When using Context Injection in ASP.Net Core(在ASP.NET核心中使用上下文注入时发生InvalidOperationException)
LINQ many-to-many relationship, how to write a correct WHERE clause?(LINQ多对多关系,如何写一个正确的WHERE子句?)