如何调用在Moq中作为参数传递的谓词?

时间:2012-10-24 16:56:27

标签: .net unit-testing mocking moq

我有一个名为:

的方法的接口
IEnumerable<string> GetFilesInADirectoryWhere(
     string directory, 
     string wildcard, 
     Predicate<string> filter);

我想Setup这种方法,实际上调用 filter。所以我宣布这样:

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

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

这个编译,但是当调用这个模拟方法时,我得到以下运行时异常:

    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)

知道我做错了吗?

1 个答案:

答案 0 :(得分:3)

您正在调用错误的Returns重载。应该是:

  • Returns<T1,T2,T3>(Func<T1,T2,T3,IEnumerable<string>>) - 匹配您方法的签名

安装程序应如下所示:

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))
    );