3

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.

Kevin Holditch
  • 5,165
  • 3
  • 19
  • 35

2 Answers2

3

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>
Fyodor Soikin
  • 78,590
  • 9
  • 125
  • 172
  • makes sense to what I was doing wrong however I have just tried that and now I get a MatchException where it was says Expected: System.Exception, Actual: was was "SqlJuxtFunctionalTests.Tests.TableBuilder.PrimaryKeyTests+should throw an exception when try to build a table with a clustered primary key referencing a nullable column@116" which I believe is the name of my function so it feels like the whole function is being match to Exception, the function is not being executed – Kevin Holditch Jan 13 '17 at 08:51
  • I think you may be misrepresenting your problem. What's the signature of your function? How exactly are you passing it? Please show your actual code. – Fyodor Soikin Jan 13 '17 at 14:20
  • signature of testException function is unit->a' Code is: ```let testException () = raise <| System.Exception() [] let ``should assert throw correctly``() = testException |> should throw typeof``` – Kevin Holditch Jan 13 '17 at 14:41
0

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.

Dave Cook
  • 53
  • 5