views:

145

answers:

1

I am new to Moq, so hopefully I am just missing something here. For some reason I am getting a TargetParameterCountException.

Can you see what I am doing wrong? Any questions? Please ask. :)

Here's my code:

[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();
  }

Here's the HasStudent method from Persistence:

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;
  }
+1  A: 

What is the signature of the FindAll method? Does your repository have overloaded FindAll methods?

If so, that may be the explanation. Your lamda expression can compile into several different types, such as Predicate<Student>, Func<Student, bool> or Expression<Func<Student, bool>>.

I'm not sure I understand exeactly what is going on, but TargetParameterCountException is a type that belongs to the System.Reflection namespace, so that indicates that Moq somehow tries to invoke a method with the wrong number of arguments. The most common cause for that is when members are overloaded and the wrong overload ends up being invoked...

Mark Seemann
Ahhhh... I see. There is also a FindAll() overload.
Alex Baranosky
Now how can I get around this without removing the FindAll() ?
Alex Baranosky
also, the signature is this: IQueryable<T> FindAll<T>(Predicate<T> predicate) { }
Alex Baranosky
or: IQueryable<T> FindAll<T>() {}
Alex Baranosky
Hmm... In that case, your Setup looks quite unambiguous, so I don't quite understand what's going on. Are both methods virtual/abstract?
Mark Seemann
neither are virtual or abstract.
Alex Baranosky
...but, to Moq them, they must be... Do they form part of an interface implementation, then (which amounts to the same thing)?
Mark Seemann