0

我正在尝试模拟下面的存储库代码:

var simulatorInstance = bundleRepository
    .FindBy<CoreSimulatorInstance>(x => x.CoreSimulatorInstanceID == instanceID)
    .Single();

但我收到一个错误,指出“序列不包含任何元素”。我尝试将 更改.SingleSingleOrDefault,但返回一个null.

在我的单元测试中,我使用以下内容模拟了我的存储库:

这不起作用

this.mockedRepository.Setup(
    x => x.FindBy<CoreSimulatorInstance>(
        z => z.CoreSimulatorInstanceID == 2))
            .Returns(coreSimulatorInstancesList.AsQueryable());

这项工作现在使用,Is.Any因为我只有一个记录

this.mockedRepository.Setup(
    x => x.FindBy<CoreSimulatorInstance>(
        It.IsAny<Expression<Func<CoreSimulatorInstance, bool>>>()))
            .Returns(coreSimulatorInstancesList.AsQueryable());

我想使用.Single.

4

1 回答 1

0

我的猜测是您正在使用 Moq 来设置存储库的FindBy方法,以便在您运行测试时业务逻辑代码命中模拟方法。

我认为问题在于 Moq 无法将您在模拟设置期间提供的参数与您在执行业务逻辑代码期间提供的参数相匹配,从而导致您的模拟存储库方法未执行coreSimulatorInstancesList且未返回。

由于您在设置期间提供给 Moq 的参数是一个表达式

z => z.CoreSimulatorInstanceID == 2

即使您的业务逻辑代码执行instanceID2

x => x.CoreSimulatorInstanceID == instanceID

导致一个与您在模拟中设置的表达式等效的表达式,它们仍然不匹配,因为它们是不同的表达式。这是两个不同的表达式对象。我认为 Moq 没有办法知道它们是等价的并基于此匹配您的模拟方法。

我会Is.Any采取方法。如果您想更彻底,我认为在这种情况下您需要手动构建一个自定义的假存储库类。

于 2013-05-01T16:04:52.307 回答