Entity framework 6 mocking include method on dbset(实体框架 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 :-
http://entityframework.codeplex.com/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 上的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:实体框架 6 模拟包含 dbset 上的方法
基础教程推荐
- 如何使用 .Net 检查 Active Directory 服务器是否已启动并正在运行? 2022-01-01
- .NET SerialPort DataReceived 事件未触发 2022-01-01
- 当值可以是对象或空数组时反序列化 JSON 2022-01-01
- 我应该在后面的代码中直接使用 Linq To SQL 还是使 2022-01-01
- 如果有人提交恶意软件Nuget包怎么办? 2022-01-01
- WPF 模态进度窗口 2022-01-01
- 禁止输入少量字符,例如'<'、'&a 2022-01-01
- Azure Functions:CosmosDBTrigger 未在 Visual Studio 中触发 2022-01-01
- Moq It.Is<>不匹配 2022-01-01
- C# 从 List<List<int>> 中删除重 2022-01-01
