Skip to content
rodrigovidal edited this page Oct 18, 2014 · 4 revisions

Foq is a lightweight thread-safe mocking library for F#, C# & VB.Net. Use Foq to mock abstract classes and interfaces.

Installation

Foq is available on Nuget: https://nuget.org/packages/Foq

Or simply include Foq.fs in your project or reference it from an F# script.

It's also bundled with AutoFixture.AutoFoq

Usage

#load "foq.fs"
open Foq

// Mock methods
let mock =
  Mock<System.Collections.IList>()
    .Setup(fun x -> <@ x.Contains(any()) @>).Returns(true)
    .Create()
mock.Contains("Anything")

// Mock properties
let mock =
  Mock<System.Collections.IList>()
    .Setup(fun x -> <@ x.Count @>).Returns(1)
    .Create()
mock.Count = 1

// Mock events
let event = Event<_,_>()
let mock =
  Mock<System.ComponentModel.INotifyPropertyChanged>()
    .SetupEvent(fun x -> <@ x.PropertyChanged @>).Publishes(event.Publish)
    .Create()
let triggered = ref false
mock.PropertyChanged.Add(fun x -> triggered := true)
event.Trigger(mock, System.ComponentModel.PropertyChangedEventArgs("PropertyName"))
triggered.Value

// Match method arguments with predicates
let mock =
  Mock<System.Collections.Generic.IList<int>>()
    .Setup(fun x -> <@ x.Remove(is(fun i -> i >= 0)) @>).Returns(true)
    .Setup(fun x -> <@ x.Remove(is(fun i -> i <  0)) @>).Raises<ArgumentOutOfRangeException>()
    .Create()
mock.Remove(99)

Implementation

Implementation Foq provides a familiar fluent interface for Moq users with strong typing via:

Foq is thread-safe.

Dependencies

Foq depends on FSharp.Core.dll which ships with Xamarin Studio on Mac and PC and in full fat Visual Studio for Windows. You can also use F# in Visual Studio Express 2012 with the F# Tools, which can also be installed on a build server. For MonoDevelop you may need to install the F# Language Bindings via the Add-In Manager. If you are using .Net 4 rather than the latest Net 4.5 in Visual Studio 2012 you may need to add a bindingRedirect to your project's app.config file (the latest Nuget package should do this for you automatically). If you are using .Net 4.5.1 or F# 3.1 in Visual Studio 2013 you can enable automatic binding redirection.

Articles

Testing and mocking your C# code with F#

Clone this wiki locally