Why is this Moq call from F # throwing an exception?
I believe it has something to do with using the times
on argument Verify()
.
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())
Exception message:
System.ArgumentException: An expression of type "System.Void" cannot be used for a constructor parameter of type "Microsoft.FSharp.Core.Unit"
source to share
The Moq Verify
method has many overloads, and without the F # annotation, it defaults to the expression you specify for the overload, expecting Func<IService,'TResult>
where 'TResult
is unit, which explains the runtime failure.
What you want to do is explicitly use an overload Verify
that takes Action
.
One option is to use the Moq.FSharp.Extensions project (available as a package on Nuget ) which, among other things, adds 2 extension methods VerifyFunc
and VerifyAction
that makes it easier to resolve F # functions for arguments Action
or Func
based on Moq C #:
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())
Another option is to use Foq , a fake Moq library specifically for F # users (also available as a Nuget package ):
open Foq
[<Test>]
let ``No worries`` () =
let mock = Mock.Of<IService>()
Mock.Verify(<@ mock.DoStuff() @>, never)
source to share