真・懒

订阅 Twitter GitHub 联系

Asserting Exceptions in FsUnit

Asserting exceptions is a feature of FsUnit, but it's hard to do it right at first try:

[<Fact>]
let ``Test bool for keypath with exn`` () =
  let jdoc = JsonDocument.Parse """{ "a" : {"b": 1}}"""
  jdoc.RootElement
  |> JPath.bool "a.b"
  |> should throw typeof<InvalidOperationException>

The correct way, is a little tricky, you must wrap the function or method that may throw exceptions inside a function:

[<Fact>]
let ``Test bool for keypath with exn`` () =
  let jdoc = JsonDocument.Parse """{ "a" : {"b": 1}}"""
  (fun () -> jdoc.RootElement |> JPath.bool "a.b" |> ignore)
  |> should throw typeof<InvalidOperationException>