2013-04-28 64 views
8

我想弄清楚如何正确测试异常与FsUnit。官方文件状态,即要测试异常我有合适的是这样的:如何正确测试例外与FsUnit

(fun() -> failwith "BOOM!" |> ignore) |> should throw typeof<System.Exception> 

但是,如果我没有记住我的测试方法与[<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 

我LogicModuleTest.fs

[<Test>] 
[<ExpectedException>] 
let``check exception``()= 
    (getNumber "") |> should throw typeof<LogicModule.EmptyStringException> 
+2

FYI - 使用Unquote,https://code.google.com/p/unquote/,你会断言你的后一个例子中的'getNumber“”'会引发预期的异常,比如'raise <@ getNumber“”@ >' – 2013-04-28 13:18:39

回答

15

已找到答案。为了检验这一异常被抛出,我应该换我的函数调用,在未来的风格:

(fun() -> getNumber "" |> ignore) |> should throw typeof<LogicModule.EmptyStringException> 

因为下面#fsunit使用的NUnit的抛出约束 http://www.nunit.org/index.php?p=throwsConstraint&r=2.5 ...这需要一个void代表,增加收益“一

+0

好的答案 - 但我不认为你需要ExpectedException属性。 – TrueWill 2013-06-09 15:09:25

+0

请注意,从lambda返回单位(即,以'|> ignore'结束有趣定义)是必需的。 – 2016-01-09 18:11:51

3

如果你想测试一个特定的异常类型是由一些代码提出,你可以添加异常类型为[<ExpectedException>]属性,如下所示:

[<Test; ExpectedException(typeof<LogicModule.EmptyStringException>)>] 
let``check exception``() : unit = 
    (getNumber "") 
    |> ignore 

更多文档可在NUnit网站上获得:http://www.nunit.org/index.php?p=exception&r=2.6.2

+0

谢谢你的回答,但我不喜欢添加一些附加属性的想法,因为当你使用FsUnit时它看起来不那么好。 – PompolutZ 2013-04-28 12:47:01