Foq icon indicating copy to clipboard operation
Foq copied to clipboard

How to mock a function (not a member)?

Open arialdomartini opened this issue 4 years ago • 0 comments

Description

While mocking a type's member is super convenient, I found no way to mock a bare function, not hosted in any type. Or, at least, I was able to mock it, but assertions seem fail.

Replacing a function with a test double requires no library: it is just a matter of defining the replacing function and using it instead of the original one. My goal, though, is then verify if the function was called and with which arguments.

When I try, I get a

Repro steps

I can easiliy replace a method with:


type MyInterface =
    abstract CallMe: string : string -> string

[<Fact>]
let ``mock a method``() =

    let mock = Mock.Of<MyInterface>()

    verify <@ mock.CallMe "Hello" @> never

    mock.CallMe "Hello"

    verify <@ mock.CallMe "Hello" @> once

If I try to do the same with a function:


type MyFunc = string -> string

[<Fact>]
let ``mock a naked function``() =

    let mock = Mock.Of<MyFunc>()

    verify <@ (mock "Hello") @> never


    mock "Hello"

    verify <@ (mock "Hello") @> once

I get a:

System.NotSupportedException
Expected function application: ValueWithName (<fun:FSharpFunc`257856397-a910-4815-8fa8-bb79a503eb1e>, mock)
   at Foq.Reflection.unwrap@736(FSharpFunc`2 toArgs', FSharpList`1 values, FSharpExpr quote)
   at [email protected](FSharpList`1 values, FSharpExpr quote)
   at Foq.Mock.DoVerify(FSharpExpr expr, Times expectedTimes)
   at SAI.AbsenceCollector.Test.Core.mock a naked function() in C:\Core.fs:line 35

The failure occurs at

verify <@ (mock "Hello") @> never

Expected behavior

I expected both the asserts to pass.

Actual behavior

A System.NotSupportedException.

Known workarounds

I found none.

Related information

  • Windows, Linux
  • Foq 1.8.0
  • .NET 5

There is a discussion on this topic on StackOverflow's Using Foq With F# Function Types

Any hints?

arialdomartini avatar Feb 14 '22 18:02 arialdomartini