Phil Trelford's Array
POKE 36879, 255

Mocking with Foq

February 13, 2013 00:43 by phil

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#.


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

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

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

    .Setup(fun x -> <@ x.Contains(any()) @>).Returns(true)

Setup a property in C# with a lambda expression:

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

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

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)


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

Categories: F# | C# | .Net
Actions: E-mail | Permalink | Comments (0) | Comment RSSRSS comment feed


Add comment

(Will show your Gravatar icon)

  Country flag

  • Comment
  • Preview