【问题标题】:How to properly test Exceptions with FsUnit如何使用 FsUnit 正确测试异常
【发布时间】:2015-08-03 18:29:54
【问题描述】:

我正在尝试弄清楚如何使用 FsUnit 正确测试异常。官方文档指出,要测试异常,我必须纠正这样的事情:

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

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

但是,只要我添加了这个属性,无论我试图抛出什么样的异常,它都会被处理。

一些sn-ps: 我的 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>

【问题讨论】:

  • 仅供参考 - 使用 Unquote,code.google.com/p/unquote,您会断言后一个示例中的 getNumber "" 会引发预期的异常,例如 raises&lt;LogicModule.EmptyStringException&gt; &lt;@ getNumber "" @&gt;

标签: f# fsunit


【解决方案1】:

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

(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

【讨论】:

  • 好答案 - 不过,我认为您不需要 ExpectedException 属性。
  • 请注意,需要从 lambda 返回单位(即,以 '|> ignore' 结束有趣的定义)。
【解决方案2】:

如果您想测试某些代码是否引发了特定的异常类型,可以将异常类型添加到[&lt;ExpectedException&gt;] 属性,如下所示:

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

NUnit 网站上提供了更多文档:http://www.nunit.org/index.php?p=exception&r=2.6.2

【讨论】:

  • 感谢您的回答,但我不喜欢添加一些额外属性的想法,因为当您使用 FsUnit 时它看起来不太好。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-11-02
  • 2018-06-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多