1

我已经使用这些 msdn 指南设置了模拟:

使用模拟框架进行测试(EF6 及以上)

var bsAc = _db.BusAcnts.FirstOrDefault(i => i.Id == 1);

返回一个帐户,但

var bsAc = _db.BusAcnts.Find(1);  

模拟时返回 null。 Find仅在使用模拟测试时失败,它在生产中运行良好。

BusAcnt:(Id 是主键)

public class BusAcnt
{
  public int Id { get; set; }
  ...
}

在此处查看我的其余设置。

在调试中,我深入了解了 Locals | 这个 | MyDbContext 和所有模拟的帐户都已加载并FirstOrDefault返回预期的帐户。

在双打的配套文章中:

使用您自己的测试替身进行测试(从 EF6 开始)

他们谈论实施Find,但这在 Mocking 文章中没有提到。

有没有其他人设法使该Find方法与模拟一起使用?

有没有其他人遇到过同样的问题,这是 EF6.1 模拟的问题还是我的代码错误?请我有兴趣听取其他人关于他们使用该Find方法进行模拟的经验。

您是否需要像测试双重文章中那样创建测试 DbSet?模拟文章中设置的语法是什么?

4

3 回答 3

4

For anyone stumbling upon this page from searching, and is using the Moq framework, I have a suggestion for how to get the Find method working as expected.

Here is the breakdown:

First, you must be using Moq and have the 'EntityFrameworkTesting.Moq' package in your test project.

In the code, when setting up your mock Context and data sets, you will likely have something similar to this:

 var users = new List<User>
        {
            new User
            {
                UserId=1,
                UserName="testUser@example.com"
            },
            new User
            {
                UserId=5,
                UserName="otherUser@example.com"
            }
        };
        var mockContext = new Mock<MyContext>();
        mockContext.Setup(x => x.Users)
            .Returns(new Mock<DbSet<User>>().SetupData(users).Object);

That last line, where the mockContext is set up, also takes a second parameter of type Func that is used to resolve the Find method. Here's how this line changes:

mockContext.Setup(x => x.Users)
    .Returns(new Mock<DbSet<User>>().SetupData(users, o => {
        return users.Single(x => x.UserId == (int)o.First());
    }).Object);

This then allows for the Find() operation to resolve correctly, using the Func that you have added as the second parameter here.

This StackOverflow post helped me reach my intended goal: https://stackoverflow.com/a/32443711

于 2016-12-04T06:27:36.823 回答
0

就在昨天,我遇到了同样的困难。

我没有找到问题的解决方案,模拟数据库集上的查找方法不起作用,它总是声称数据库集应该为空,但实际上不可能是真的,因为相同的模拟代码将与 Where或单个表达式而不是查找。

这也是我的解决方法。我将查找更改为单项。

于 2014-06-11T07:29:52.967 回答
0

使用 EntityFrameworkMock.Moq,这将抽象出所有的模拟问题。

于 2019-04-11T20:47:29.250 回答