Steve Dunn
Steve Dunn

Reputation: 21761

How do I call a predicate passed as a parameter in Moq?

I've got an interface which has a method named:

IEnumerable<string> GetFilesInADirectoryWhere(
     string directory, 
     string wildcard, 
     Predicate<string> filter);

I want to Setup this method and actually call the filter. So I declared it like this:

myMock.Setup( x => x.GetFilesInADirectoryWhere(
    @"My Folder", 
    @"FooFile*.*", 
    It.IsAny<Predicate<string>>()))

    .Returns((Predicate<string> filter) =>  
        cannedFileNames.Where(filename=>filter(filename)));

This compiles, but when this mocked method is called, I get the following runtime exception:

    SetUp : System.Reflection.TargetParameterCountException : Parameter count mismatch.
       at System.Reflection.RuntimeMethodInfo.InvokeArgumentsCheck(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
       at System.Delegate.DynamicInvokeImpl(Object[] args)
       at Moq.Extensions.InvokePreserveStack(Delegate del, Object[] args)
       at Moq.MethodCallReturn`2.Execute(ICallContext call)
       at Moq.Interceptor.Intercept(ICallContext invocation)
       at Moq.Proxy.CastleProxyFactory.Interceptor.Intercept(IInvocation invocation)
       at Castle.DynamicProxy.AbstractInvocation.Proceed()
       at Castle.Proxies.IDiskProxy.GetFilesInADirectoryWhere(String directory, String filter, Predicate`1 predicate)

Any idea what I'm doing wrong?

Upvotes: 3

Views: 509

Answers (1)

k.m
k.m

Reputation: 31454

You're invoking wrong Returns overload. Should be:

  • Returns<T1,T2,T3>(Func<T1,T2,T3,IEnumerable<string>>) - matching your method's signature

Setup should look like:

myMock
    .Setup(m => m.GetFilesInADirectoryWhere(
        @"My Folder", 
        @"FooFile*.*", 
        It.IsAny<Predicate<string>>())
    )
    .Returns<string, string, Predicate<string>>((dir, wildcard, filter) =>  
        cannedFileNames.Where(filename => filter(filename))
    );

Upvotes: 3

Related Questions