实体框架 6 模拟包含 dbset 上的方法

编程入门 行业动态 更新时间:2024-10-09 06:31:25
本文介绍了实体框架 6 模拟包含 dbset 上的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

一直在谷歌上搜索有关如何在 EF6 中模拟 dbset 上的 include 方法的问题的解决方案.这个问题在这里有很好的记录:-

Have been googling for a solution to the problem on how to mock the include method on dbset in EF6. The problem is well documented here :-

entityframework.codeplex/discussions/461731

很遗憾,尽管其中似乎没有有效的解决方案.

Unfortunately though there does not seem to be a valid solution in there.

有没有人找到解决方法?

Has anyone found a workaround to this?

我明白我们不应该真的嘲笑 EF6 上下文,但项目负责人坚持这样做.

I do understand that we shouldn't really be mocking the EF6 context, but the project lead has insisted on it.

提前致谢.

推荐答案

所以,如果有点小问题,这是可能的!

So, this is possible if a bit of a faff!

在下面我设置了模拟上下文并设置并且可以成功调用包含.我认为秘诀在于对 Provider、Expression 和 GetEnumerator 的调用进行存根,并将存根上下文上的 DbSet 属性设置为存根集,而不是将上下文存根以返回它们.

In the below I setup the mock context and sets and can call include successfully. I think that the secret sauce is in stubbing the calls through to Provider, Expression and GetEnumerator and in setting the DbSet properties on the stubbed context to the stubbed sets and not stubbing the context to returning them.

GitHub 上有一个可运行的示例

[Test] public void CanUseIncludeWithMocks() { var child = new Child(); var parent = new Parent(); parent.Children.Add(child); var parents = new List<Parent> { parent }.AsQueryable(); var children = new List<Child> { child }.AsQueryable(); var mockContext = MockRepository.GenerateStub<TestContext>(); var mockParentSet = MockRepository.GenerateStub<IDbSet<Parent>>(); var mockChildSet = MockRepository.GenerateStub<IDbSet<Child>>(); mockParentSet.Stub(m => m.Provider).Return(parents.Provider); mockParentSet.Stub(m => m.Expression).Return(parents.Expression); mockParentSet.Stub(m => m.GetEnumerator()).Return(parents.GetEnumerator()); mockChildSet.Stub(m => m.Provider).Return(children.Provider); mockChildSet.Stub(m => m.Expression).Return(children.Expression); mockChildSet.Stub(m => m.GetEnumerator()).Return(children.GetEnumerator()); mockContext.Parents = mockParentSet; mockContext.Children = mockChildSet; mockContext.Parents.Should().HaveCount(1); mockContext.Children.Should().HaveCount(1); mockContext.Parents.First().Children.FirstOrDefault().Should().NotBeNull(); var query = mockContext.Parents.Include(p=>p.Children).Select(pc => pc); query.Should().NotBeNull().And.HaveCount(1); query.First().Children.Should().NotBeEmpty().And.HaveCount(1); }

更多推荐

实体框架 6 模拟包含 dbset 上的方法

本文发布于:2023-11-15 06:27:08,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1591956.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:实体   框架   方法   dbset

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!