【发布时间】:2014-08-07 12:08:18
【问题描述】:
我正在尝试模拟我的存储库层,并且我有一个方法 GetSelection(Expression<Func<T, Boolean>> where)。我正在使用 Ninjects MickingKernel 和 Moq 来实现这一点。
当我执行以下操作时,很好:
// 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