如何使用FsUnit正确测试异常

Pom*_*utZ 10 f# fsunit

我试图找出如何使用FsUnit正确测试异常.官方文档指出,要测试异常,我必须这样:

(fun () -> failwith "BOOM!" |> ignore) |> should throw typeof<System.Exception>
Run Code Online (Sandbox Code Playgroud)

但是,如果我没有用[<ExpectedException>]属性标记我的测试方法,它将始终失败.听起来很合理,因为如果我们想测试异常,我们必须在C#+ NUnit中添加这样的属性.

但是,只要我添加了这个属性,我试图抛出什么样的异常并不重要,它将始终处理.

一些片段:我的LogicModule.fs

exception EmptyStringException of string

let getNumber str =
    if str = "" then raise (EmptyStringException("Can not extract number from empty string"))
    else int str
Run Code Online (Sandbox Code Playgroud)

我的LogicModuleTest.fs

[<Test>]
[<ExpectedException>]
let``check exception``()=
    (getNumber "") |> should throw typeof<LogicModule.EmptyStringException>
Run Code Online (Sandbox Code Playgroud)

Pom*_*utZ 16

已找到答案.为了测试抛出异常,我应该在下一个样式中包装我的函数调用:

(fun () -> getNumber "" |> ignore) |> should throw typeof<LogicModule.EmptyStringException>
Run Code Online (Sandbox Code Playgroud)

因为#fsunit下面使用了NUnit的Throws约束 http://www.nunit.org/index.php?p=throwsConstraint&r=2.5 ...它取了一个void的委托,raise返回'a