Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSubstitute and FSharp - Mocking an FSharp Function

Tags:

mocking

f#

Given an interface that has a FSharp style function.

type IUseless =
    abstract member Listify: string -> int -> string list

How would you mock the function?

let substitute = NSubstitute.Substitute.For<IUseless>()
substitute.Listify.Returns(??? what would even go here ???)

I wouldn't expect to be able to mock it like a normal method, or a value that contains a function (although that's sort of what it represents).

So I'm curious if anyone has successfully mocked an FSharp function with a typical .NET mocking library.

like image 685
Daniel Little Avatar asked Oct 15 '25 19:10

Daniel Little


1 Answers

First: yes, you can totally mock this like a normal method:

let substitute = NSubstitute.Substitute.For<IUseless>()
(substitute.Listify "abc" 5).Returns ["whatevs"]

This works, because F# compiles this definition like a normal .NET method, despite the curried syntax. This is done partly for interop and partly for performance.

But second: if I were you, I would rather skip the whole NSubstitute business altogether and use inline interface implementation instead:

let substitute = { new IUseless with member x.Listify a b = ["whatevs"] }

This is cleaner, better typechecked, and a lot faster at runtime.

like image 80
Fyodor Soikin Avatar answered Oct 18 '25 15:10

Fyodor Soikin