moodmosaic (Nikos Baxevanis)
Blog - About - Open Source - Bookmarks - Tags

Auto-Mocking with Foq and AutoFixture

Saturday, 19 October 2013

A new Auto-mocking extension have been recently added to AutoFixture allowing the mock instances to be created by Foq.

This brings the total number of Auto-mocking extensions for AutoFixture up to five:


To install AutoFixture with Auto Mocking using Foq, run the following command in the Package Manager Console:

PM> Install-Package AutoFixture.AutoFoq

To use it, add an AutoFoqCustomization to the Fixture instance:

let fixture = Fixture().Customize(AutoFoqCustomization())


In the test below the mocked instance is created automatically by Foq:

let AutoMockInterfaceAndSetupExpectations() =
    // Fixture setup
    let fixture = Fixture().Customize(AutoFoqCustomization())
    let dummy = obj()
    // Exercise system
    let sut = fixture.Create<IInterface>()
    sut.MakeIt(dummy) |> ignore
    // Verify outcome
    Mock.Verify(<@ sut.MakeIt(dummy) @>, Times.Once)
    // Teardown

The above test can be written declaratively using AutoData theories:

let AutoMockInterfaceAndSetupExpectationsDeclaratively
  (sut: IInterface, dummy: obj) =
    sut.MakeIt(dummy) |> ignore
    Mock.Verify(<@ sut.MakeIt(dummy) @>, Times.Once)

The [AutoFoqData] attribute is defined as:

type AutoFoqDataAttribute() =
    inherit AutoDataAttribute(

An automatically published release created from the latest successful build can be also downloaded from here.


This post has been filed under #f# #autofixture


Have feedback on this page? Let @nikosbaxevanis know on twitter. Need help or found a bug? Contact me.

© 2011-2018 Nikos Baxevanis. All written content on this site is provided under a Creative Commons ShareAlike license. All code is provided under a MIT license unless otherwise stated.