Skip to content

Instantly share code, notes, and snippets.

@jwosty
Created May 26, 2022 23:06
Show Gist options
  • Select an option

  • Save jwosty/0ca4eb69e2226b39d11144d35648ee62 to your computer and use it in GitHub Desktop.

Select an option

Save jwosty/0ca4eb69e2226b39d11144d35648ee62 to your computer and use it in GitHub Desktop.
type Mock =
// poor man's Moq, for individual functions!
static member SetupFunction (funcName, funcImpl) =
let mutable argsState = []
let theMockFunc arg =
argsState <- argsState @ [arg]
funcImpl arg
theMockFunc, {|
calledOnce =
fun () ->
match argsState with
| [] -> failwithf "Expected %s to be called; but was never called" funcName
| [_] -> ()
| _ -> failwithf "Expected %s to be called once; but was called %i times" funcName argsState.Length
neverCalled =
fun () ->
match argsState with
| [] -> ()
| _ -> failwithf "Expected %s to never be called; but was called %i times" funcName argsState.Length
calledWithArg =
fun expectedArg ->
match argsState with
| [] -> failwithf "Expected %s to be called; but was never called" funcName
| _ ->
let lastArgActual = List.last argsState
if lastArgActual <> expectedArg then failwithf "Incorrect argument passed to %s:\nExpected: %A\nGot: %A" funcName expectedArg (List.last argsState)
calledManyWithArgs =
fun (expectedArgs: _ list) ->
match argsState with
| [] -> failwithf "Expected %s to be called at least once; but was never called" funcName
| _ ->
if argsState.Length <> expectedArgs.Length then
failwithf "Expected %s to be called %i times; but was called %i times:\nExpected arg sequence: %A\nGot arg sequence: %A" funcName expectedArgs.Length argsState.Length expectedArgs argsState
else
expectedArgs |> Seq.zip argsState
|> Seq.iteri (fun i (expectedArg, actualArg) ->
if actualArg <> expectedArg then
failwithf "Call #%i got the wrong argument:\nExpected: %A\nGot: %A" i expectedArg actualArg
)
|}
static member SetupFunction (funcName) = Mock.SetupFunction (funcName, ignore)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment