簡體   English   中英

使用Moq:mock對象拋出'TargetParameterCountException'

[英]Using Moq: mock object throwing 'TargetParameterCountException'

我是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;
  }

這是問題的遲到但是為了Google員工......

我有一個非常類似的情況,我無法解釋原因,但問題似乎是在.Returns()內的泛型List上調用AsQueryable。 通過在模擬設置之前將List設置為IQueryable來解決問題。 就像是...

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

FindAll方法的簽名是什么? 您的存儲庫是否重載了FindAll方法?

如果是這樣,那可能就是解釋。 你的lamda表達式可以編譯成幾種不同的類型,例如Predicate<Student>Func<Student, bool>Expression<Func<Student, bool>>

我不確定我是否正在理解發生了什么,但TargetParameterCountException是一個屬於System.Reflection命名空間的類型,因此這表明Moq以某種方式嘗試使用錯誤數量的參數調用方法。 最常見的原因是當成員超載並且錯誤的重載最終被調用時...

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM