2015-05-09 72 views
3

我认为这与使用times论点Verify()有关。为什么从F#调用Moq会引发异常?

open NUnit.Framework 
open Moq 

type IService = abstract member DoStuff : unit -> unit 

[<Test>] 
let ``Why does this throw an exception?``() = 
    let mockService = Mock<IService>() 
    mockService.Verify(fun s -> s.DoStuff(), Times.Never()) 

异常消息:

System.ArgumentException:不能用于类型的构造器参数类型的 'System.Void' 表达 'Microsoft.FSharp.Core.Unit'

回答

5

Moq的Verify方法有很多重载,并且没有注释F#默认会解析您指定的表达式,以期望Func<IService,'TResult>,其中'TResult是单位,这解释了在失败时失败我。

你想要做的是明确使用Verify的过载,其中需要Action

一种选择是使用Moq.FSharp.Extensions项目(可作为Nuget包),它除其他外增加了2种扩展方法VerifyFunc & VerifyAction使其更容易以解决F#功能,以起订量的C#ActionFunc参数:

open NUnit.Framework 
open Moq 
open Moq.FSharp.Extensions 

type IService = abstract member DoStuff : unit -> unit 

[<Test>] 
let ``Why does this throw an exception?``() = 
    let mockService = Mock<IService>() 
    mockService.VerifyAction((fun s -> s.DoStuff()), Times.Never()) 

另一种选择是使用Foq,一个起订量等嘲笑文库专门为F#用户设计(也可作为Nuget package):

open Foq 

[<Test>] 
let ``No worries``() = 
    let mock = Mock.Of<IService>() 
    Mock.Verify(<@ mock.DoStuff() @>, never) 
+1

我想你的意思是nuget包添加了VerifyFunc和VerifyAction扩展方法,而不是重载。 – Andy

相关问题