2012-10-24 82 views
3

我有其中有一個名爲方法的接口:如何調用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) 

任何想法,我做錯了嗎?

回答

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