Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to mock a function (not a member)? #34

Open
arialdomartini opened this issue Feb 14, 2022 · 0 comments
Open

How to mock a function (not a member)? #34

arialdomartini opened this issue Feb 14, 2022 · 0 comments

Comments

@arialdomartini
Copy link

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 Foq.Reflection.unwrap@736-1.Invoke(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?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant