Phillip Trelford's Array

POKE 36879,255

Moq.FSharp.Extensions

F# 3 brings first-class support for LINQ Expressions, which makes working with libraries like Moq and FluentValidation easy. A while back I wrote about using Moq with F# 3 and introduced some extension methods to improve the experience for F#. I’ve created a small project called the Moq.FSharp.Extensions currently hosted on BitBucket (the library is about 50 lines of code in a single file), it is also available to download as a Nuget package.

End extension

One thing that was bugging me about using Moq in F# was having to end method setups by ignoring the builder result (in F# you must explicitly ignore return values):

mock.SetupFunc(fun foo -> foo.DoSomething("ping")).Returns(true) |> ignore

While reading Ramon Snir’s answer to using the FluentValidation library in F# over on Stack Overflow, where he adds an Ignore extension method to the builder, it occurred to me to add an End extension method to explicitly end Moq builders:

mock.SetupFunc(fun foo -> foo.DoSomething("ping")).Returns(true).End

any() function

The extensions include some ideas taken from Foq, my own .Net mocking library built for F#. One of the ideas is an any() function which uses F#’s powerful type inference for setting up method arguments on mocks which I find a little easier on the eye than It.IsAny<_>():

mock.SetupFunc(fun foo -> foo.DoSomething(It.IsAny<string>())).Returns(true).End

becomes:

mock.SetupFunc(fun foo -> foo.DoSomething(any()).Returns(true).End

mock function()

The Moq.FSharp.Extensions project includes some examples based on:

The final test in the warehouse example demonstrates the mock() function:

let [<Test>] ``order sends mail if unfilled`` () =
    // setup data
    let order = Order("TALISKER", 51)
    let mailer = mock()
    order.SetMailer(mailer)
    // exercise
    order.Fill(mock())
    // verify
    Mock.Get(mailer).VerifyAction(fun mock -> mock.Send(any()))

Above you can see no type annotations are required at all.

Foq or Moq

The extensions bring some of the ease of use for F# of Foq to Moq. If your tests need to run with F# 2 (Visual Studio 2010) then Foq is a better option as it supports F# Quotations, as well as LINQ Expressions. Otherwise I guess it’s just a matter of taste :)

Pingbacks and trackbacks (1)+

Comments are closed