【问题标题】:Mocking with anonymous parameter使用匿名参数模拟
【发布时间】:2014-08-07 12:08:18
【问题描述】:

我正在尝试模拟我的存储库层,并且我有一个方法 GetSelection(Expression<Func<T, Boolean>> where)。我正在使用 Ninjects MickingKernelMoq 来实现这一点。

当我执行以下操作时,很好:

// Create instance of repository
var kernel = new MoqMockingKernel();
var templateRepoMock = kernel.GetMock<ITemplateRepo>();

// Setup mock
templateRepoMock.Setup(x=>x.GetSelection(y=>y.FieldName)
                .Returns(new List<Template>() {new Template { ... })); 
                // Lets pretend that FieldName is a bool!

// Call Service layer
var result = templateService.MyMethod();

// -> Service Layer method
public List<Template> MyMethod() 
{
    return _templateRepo.GetSelection(x=>x.FieldName);
}

但是当我尝试在我的表达式中添加一个额外的参数时,我得到一个ArgumentNullExeption

// Setup mock 
templateRepoMock.Setup(x=>x.GetSelection(y=>y.SomeOtherField.Id == 1 
                                         && y.FieldName)
                .Returns(new List<Template>() {new Template { ... }));

当我将服务更新为以下内容时:

public List<Template> MyMethod(SomeObject myObject) 
{
    return _templateRepo.GetSelection(x=>x.SomeObject.Id == myObject.Id 
                                      && x.FieldName).ToList(); 
}

如果我将 myObject.Id 更新为 1 似乎没问题。

任何想法为什么会发生这种情况?

【问题讨论】:

  • 我已经编辑了你的标题。请参阅“Should questions include “tags” in their titles?”,其中的共识是“不,他们不应该”。
  • 我总是非常仔细地考虑我的帖子的内容 - 可惜我忘了省略这个。
  • 我复制并运行了您的代码,但没有看到任何异常。异常在哪里抛出?您能否包含更多可能相关的代码?您使用的是什么版本的起订量?另外,如果您还没有,请尝试在单独的项目中自己复制它;也许你会得到和我一样的结果。
  • 服务层抛出异常——不在测试中
  • 这里是我使用的版本:

标签: c# moq ninject-mockingkernel


【解决方案1】:

仍然没有看到您所做的异常,即使在使用您的 Github 项目时也是如此。相反,测试在 VerifyAll 行失败并显示以下消息:

Moq.MockVerificationException : 以下设置不匹配:

IProductRepository mock => mock.GetProducts(x => x.Name == "Test" && x.IsActive)

但是,我认为您可能在追逐红鲱鱼,因为 Moq 不支持设置采用 Expression 的方法。见this answer

【讨论】:

  • 天啊,回答了它。谢谢你帮我解决这个问题!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-05-22
  • 1970-01-01
  • 1970-01-01
  • 2015-10-29
相关资源
最近更新 更多