我是 Moq 的新手,所以希望我只是在这里遗漏了一些东西。出于某种原因,我收到了 TargetParameterCountException。
你能看出我做错了什么吗?任何问题?请问。 :)
这是我的代码:
[Test]
public void HasStudentTest_SaveToRepository_Then_HasStudentReturnsTrue()
{
var fakeStudents = new List<Student>();
fakeStudents.Add(new Student("Jim"));
mockRepository.Setup(r => r.FindAll<Student>(It.IsAny<Predicate<Student>>()))
.Returns(fakeStudents.AsQueryable<Student>)
.Verifiable();
// in persistence.HasStudent(), repo.FindAll(predicate) is throwing
// 'TargetParameterCountException' ; not sure why
persistence.HasStudent("Jim");
mockRepository.VerifyAll();
}
这是 Persistence 的 HasStudent 方法:
public bool HasStudent(string name)
{
// throwing the TargetParameterCountException
var query = Repository.FindAll<Student>(s => s.Name == name);
if (query.Count() > 1)
throw new InvalidOperationException("There should not be multiple Students with the same name.");
return query.Count() == 1;
}
最佳答案
FindAll 方法的签名是什么?您的存储库是否重载了 FindAll 方法?
如果是这样,这可能就是解释。您的 lamda 表达式可以编译成几种不同的类型,例如 Predicate<Student>
、 Func<Student, bool>
或 Expression<Func<Student, bool>>
。
我不确定我完全理解发生了什么,但 TargetParameterCountException 是属于 System.Reflection 命名空间的类型,因此这表明 Moq 以某种方式尝试调用具有错误数量参数的方法。最常见的原因是成员过载并且最终调用了错误的过载......
关于c# - 使用最小起订量 : mock object throwing 'TargetParameterCountException' ,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/1625945/