Using Moq: mock object throwing 'TargetParameterCountException'

I am new to Moq, so hopefully I just missed something here. For some reason, I get a TargetParameterCountException exception.

Do you see what I'm doing wrong? Any questions? Please ask. :)

Here is 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;
  }
+3
source share
2 answers

What is the signature of the FindAll method? Are FindAll methods overloaded in your repository?

If so, this may be an explanation. Your lamda expression can be compiled into several different types, for example Predicate<Student>, Func<Student, bool>or Expression<Func<Student, bool>>.

, , , TargetParameterCountException - , System.Reflection, , Moq - . , , ...

+3

, ...

, , , AsQueryable .Returns(). IQueryable . - ...

var fakeList = new List<foo>.AsQueryable();
...
mockRepository.Setup(r => r.FindAll<foo>(It.IsAny<foo>()))
                            .Returns(fakeList)
                            .Verifiable();
+5

Source: https://habr.com/ru/post/1721105/


All Articles