0

如何断言 FsUnit 中的异常消息?来自 NUnit 的类似内容:

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

编辑:我不关心异常本身,我想测试异常 MESSAGE。

4

1 回答 1

3

AFAIK 没有开箱即用的匹配器来做你想做的事,但你自己创建一个很容易:

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 )

用法:

(fun () -> raise <| Exception("Foo") |> ignore) |> should throwAnyWithMessage "Foo" // pass
(fun () -> raise <| Exception("Bar") |> ignore) |> should throwAnyWithMessage "Foo" // fail
于 2015-08-03T17:06:49.560 回答