Moq Params TargetParameterCountException : Parameter count mismatch Exception

前端 未结 4 650
囚心锁ツ
囚心锁ツ 2020-12-10 05:15

Following is my generic base repository interface

public interface IRepository
{
    IQueryable AllIncluding(params Expression

        
相关标签:
4条回答
  • 2020-12-10 05:47

    I think you've hit some limitations here with Moq. It doesn't handle expression parameters well because it can be passed expressions as values itself. There's no way for Moq to know what part of the expression is intended to be resolved and what is part of the signature.

    Also, I can't remember how well Moq handles params xx[] but it's quite possible you have a combination of two problems here.

    Are you able to create a class that exposes the set of expressions as a property? If so it might be possible to change the signature of AllIncluding and tell Moq to match on any instance of that class.

    Update

    At the time of answering this was a limitation but is now possible. See the answer by Oleksandr Lytvyn

    0 讨论(0)
  • 2020-12-10 05:48

    Though there is an answer marked as accepted, I believe there is a way to mock your repository correctly.

    Instead of

    mockRepo.Setup(k => k.AllIncluding(It.IsAny<Expression<Func<Sdk, object>>[]>()))
                         .Returns(sdks.AsQueryable);
    

    please use

    mockRepo.Setup(k => k.AllIncluding(It.IsAny<Expression<Func<Sdk, object>>[]>()))
                         .Returns((Expression<Func<Sdk, 
                            object>>[] includeProperties) => sdks.AsQueryable());
    
    0 讨论(0)
  • 2020-12-10 05:57

    For other people looking for answer to this the solution for me was adding the same number of parameters in Setup as in the expression in Returns.

    For example:

    Not working with different argument count

    mock.Setup(x => x.DoSomething(It.IsAny<string>(), It.IsAny<string>()))
                    .Returns((string s) => s.ToLower());
    

    Working with same amount of args in expression in Returns as in Setup

    mock.Setup(x => x.DoSomething(It.IsAny<string>()))
                    .Returns((string s1, string s2) => s1.ToLower());
    
    0 讨论(0)
  • 2020-12-10 05:58

    Another solution for solving this issue is to use: .AsQueryable() instead of .AsQueryable.

    0 讨论(0)
提交回复
热议问题