我是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以某种方式尝试使用错误数量的参数调用方法。最常见的原因是当成员超载并且错误的重载最终被调用时......

其他提示

这个问题迟到了,但为了Google员工......

我有一个非常类似的情况,我无法解释原因,但问题似乎是在.Returns()内的通用List上调用AsQueryable。通过在模拟设置之前将List设置为IQueryable来解决问题。有点像...

var fakeList = new List<foo>.AsQueryable();
...
mockRepository.Setup(r => r.FindAll<foo>(It.IsAny<foo>()))
                            .Returns(fakeList)
                            .Verifiable();
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top