FsUnit断言异常消息

时间:2015-08-03 07:23:26

标签: f# fsunit

如何在FsUnit中断言异常消息?来自NUnit的东西:

[<Test>]
let ShouldThrowExceptionAndLog() = 
    Assert.That
        ((fun () -> Calculator.Calculate "-1"), 
         Throws.Exception.With.Property("Message").EqualTo("Negatives not allowed: -1"))
编辑:我不关心异常本身,我想测试异常MESSAGE。

1 个答案:

答案 0 :(得分: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