Search code examples
f#fsunit

Asserting exception in FsUnit F# for XUnit


I am trying to assert that an exception was thrown. Here is a cut down piece of code that reproduces the problem:

open FsUnit
open Xunit

let testException () =
    raise <| Exception()

[<Fact>]
let ``should assert throw correctly``() =
    (testException ())
        |> should throw typeof<System.Exception>

The error says that a System.Exception was thrown but the test should pass as that is what I am asserting. Can someone please help with where I am going wrong.


Solution

  • You're calling the testException function, and then passing its result as argument to the should function. At runtime, testException crashes, and so never returns a result, and so the should function is never called.

    If you want the should function to catch and correctly report the exception, you need to pass it the testException function itself, not its result (for there is no result in the first place). This way, the should function will be able to invoke testException within a try..with block and thus catch the exception.

    testException |> should throw typeof<System.Exception>