0

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

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

// 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,这似乎很好。

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

4

1 回答 1

1

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

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

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

但是,我认为您可能正在追逐红鲱鱼,因为 Moq 不支持设置采用Expression. 看到这个答案

于 2014-08-07T15:28:51.790 回答