如何使用FsUnit正确测试异常 [英] How to properly test Exceptions with FsUnit
问题描述
我正在尝试找出如何使用FsUnit正确测试异常的方法.官方文档指出,要测试例外情况,我必须纠正以下内容:
I'm trying to figure out how to properly test exceptions with FsUnit. Official documentation states, that to test for exceptions I have to right something like this:
(fun () -> failwith "BOOM!" |> ignore) |> should throw typeof<System.Exception>
但是,如果我不使用[<ExpectedException>]
属性标记测试方法,它将始终失败.听起来很合理,因为如果我们要测试异常,则必须在C#+ NUnit中添加此类属性.
But, if I don't mark my test method with [<ExpectedException>]
attribute it will always fail. Sounds reasonable because if we want to test for exceptions we have to add such attribute in C# + NUnit.
但是,只要我添加了此属性,无论我尝试引发哪种异常都无所谓,它将始终得到处理.
But, as long as I've added this attribute it doesn't matter what kind of exception I'm trying to throw, it will be always handled.
一些摘要: 我的LogicModule.fs
Some snippets: My 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
My LogicModuleTest.fs
[<Test>]
[<ExpectedException>]
let``check exception``()=
(getNumber "") |> should throw typeof<LogicModule.EmptyStringException>
推荐答案
已找到答案.要测试是否引发了异常,我应该使用下一种样式包装函数调用:
Answer has been found. To test that exception was thrown I should wrap my function call in the next style:
(fun () -> getNumber "" |> ignore) |> should throw typeof<LogicModule.EmptyStringException>
因为在#fsunit下面使用了NUnit的Throws约束 http://www.nunit.org/index.php?p=throwsConstraint&r=2.5 …需要一个void的代表,raise返回'a
because underneath #fsunit uses NUnit's Throws constraint http://www.nunit.org/index.php?p=throwsConstraint&r=2.5 … which takes a delegate of void, raise returns 'a
这篇关于如何使用FsUnit正确测试异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!