我正在尝试弄清楚如何正确地使用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>发布于 2013-04-28 20:45:17
答案已经找到了。为了测试抛出的异常,我应该将我的函数调用包装成下一个样式:
(fun () -> getNumber "" |> ignore) |> should throw typeof<LogicModule.EmptyStringException>因为下面的#fsunit使用NUnit的抛出约束http://www.nunit.org/index.php?p=throwsConstraint&r=2.5…它接受void的委托,raise返回'a
发布于 2013-04-28 20:44:50
如果您想测试某个特定的异常类型是否由某些代码引发,可以将该异常类型添加到[<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
https://stackoverflow.com/questions/16261497
复制相似问题