简体   繁体   中英

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.

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>

This seems to do the trick:

[<Fact>]
let ``should assert throw correctly``() =
    (fun () -> Exception() |> raise |> ignore)
        |> should throw typeof<System.Exception>

Not really sure why the ignore is required tbh. Not found anything to explain this.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM