Phillip Trelford's Array

POKE 36879,255

Mocking with Foq

Foq is an open source .Net mocking library with a familiar fluent API for Moq users that lets you setup mock object using either LINQ or F# Code Quotations. Moq was developed to take advantage of .Net 3.5 LINQ expression trees and C# 3.0 features. Foq has been designed to provide first-class support for users of both C# and F#. C# users can use the LINQ API while F# users can choose between the LINQ API and Code Quotations. We use F# as a unit testing language at work and Foq for mocking code written in both C# and F#.

Examples

Setup a mock method in C# with a lambda expression:

new Mock<IList<int>>()
    .SetupFunc(x => x.Contains(It.IsAny<int>())).Returns(true)
    .Create();

Setup a mock method in F# with a Code Quotation:

Mock<System.Collections.IList>()
    .Setup(fun x -> <@ x.Contains(any()) @>).Returns(true)
    .Create()

Setup a property in C# with a lambda expression:

new Mock<IList<int>>()
    .SetupPropertyGet(x => x.Count).Returns(1)
    .Create();

Setup multiple properties in C# with an anonymous object:

new Mock<IOrder>()
    .SetupProperties(new {
        Price = 99.99M,
        Quantity = 10,
        Side = Side.Bid,
        TimeInForce = TimeInForce.GoodTillCancel
    })
.Create();

Setup multiple members in F# with a Code Quotation:

Mock<IList<char>>.With(fun xs ->
    <@ xs.Count --> 2 
        xs.Item(0) --> '0'
        xs.Item(1) --> '1'
        xs.Contains(any()) --> true
        xs.RemoveAt(2) ==> System.ArgumentOutOfRangeException()
    @>
)

Verify a method was called in C#:

Mock.VerifyFunc(() => list.Contains(1));

Verify a method was called once in F#:

Mock.Verify(<@ xs.Contains(any()) @>, once)

Download

Foq is available on Nuget or for F# projects you can just include the Foq.fs source file.

Comments are closed