0

How to assert on exception message in FsUnit? Something like this from NUnit:

[<Test>]
let ShouldThrowExceptionAndLog() = 
    Assert.That
        ((fun () -> Calculator.Calculate "-1"), 
         Throws.Exception.With.Property("Message").EqualTo("Negatives not allowed: -1"))

EDIT: I don't care about the exception itself, I'd like to test the exception MESSAGE.

user963935
  • 493
  • 4
  • 20
  • 1
    possible duplicate of [How to properly test Exceptions with FsUnit](http://stackoverflow.com/questions/16261497/how-to-properly-test-exceptions-with-fsunit) – Mark Seemann Aug 03 '15 at 10:30
  • I think the related question just checks that a specific exception has been thrown - not that it contains specified message... – Tomas Petricek Aug 03 '15 at 12:03

1 Answers1

3

AFAIK there is no out-of-the-box matcher to do what you want, but it's easy enough to create one yourself:

open NHamcrest

let throwAnyWithMessage m =
    CustomMatcher<obj>(m,
        fun f -> match f with
                    | :? (unit -> unit) as testFunc ->
                        try
                            testFunc()
                            false
                        with
                        | ex -> ex.Message = m
                    | _ -> false )

usage:

(fun () -> raise <| Exception("Foo") |> ignore) |> should throwAnyWithMessage "Foo" // pass
(fun () -> raise <| Exception("Bar") |> ignore) |> should throwAnyWithMessage "Foo" // fail
CaringDev
  • 8,391
  • 1
  • 24
  • 43