首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何使用FsUnit正确测试异常

如何使用FsUnit正确测试异常
EN

Stack Overflow用户
提问于 2013-04-28 17:30:43
回答 2查看 2.4K关注 0票数 12

我正在尝试弄清楚如何正确地使用FsUnit测试异常。官方文档指出,要测试异常,我必须纠正以下内容:

代码语言:javascript
复制
(fun () -> failwith "BOOM!" |> ignore) |> should throw typeof<System.Exception>

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

但是,只要我添加了这个属性,我尝试抛出的是哪种类型的异常都无关紧要,它将始终得到处理。

一些代码片段:我的LogicModule.fs

代码语言:javascript
复制
exception EmptyStringException of string

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

我的LogicModuleTest.fs

代码语言:javascript
复制
[<Test>]
[<ExpectedException>]
let``check exception``()=
    (getNumber "") |> should throw typeof<LogicModule.EmptyStringException>
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2013-04-28 20:45:17

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

代码语言:javascript
复制
(fun () -> getNumber "" |> ignore) |> should throw typeof<LogicModule.EmptyStringException>

因为下面的#fsunit使用NUnit的抛出约束http://www.nunit.org/index.php?p=throwsConstraint&r=2.5…它接受void的委托,raise返回'a

票数 17
EN

Stack Overflow用户

发布于 2013-04-28 20:44:50

如果您想测试某个特定的异常类型是否由某些代码引发,可以将该异常类型添加到[<ExpectedException>]属性中,如下所示:

代码语言:javascript
复制
[<Test; ExpectedException(typeof<LogicModule.EmptyStringException>)>]
let``check exception`` () : unit =
    (getNumber "")
    |> ignore

有关更多文档,请访问NUnit网站:http://www.nunit.org/index.php?p=exception&r=2.6.2

票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/16261497

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档