【问题标题】:How do I call a predicate passed as a parameter in Moq?如何调用在 Moq 中作为参数传递的谓词?
【发布时间】:2012-10-24 16:56:26
【问题描述】:

我有一个接口,它有一个名为:

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)

知道我做错了什么吗?

【问题讨论】:

    标签: .net unit-testing mocking moq


    【解决方案1】:

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

    • Returns&lt;T1,T2,T3&gt;(Func&lt;T1,T2,T3,IEnumerable&lt;string&gt;&gt;) - 匹配你方法的签名

    设置应如下所示:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-01-13
      • 1970-01-01
      • 2012-06-16
      • 1970-01-01
      • 1970-01-01
      • 2011-10-22
      相关资源
      最近更新 更多