如何在 F# 中使用 nUnit 捕获 failwith?
how to catch a failwith with nUnit in F#?
假设我有这个代码:
let a () =
failwith "I want to fail!"
然后我有一个 nUnit 测试:
Assert.Throws(fun () -> a() |> ignore)
测试将 return:
Method has non-void return value, but no result is expected
Exception doesn't have a stacktrace
如何测试出现预期故障情况的用例?
有几个关于异常的问题/答案,但我没有找到 failwith 案例的答案。
你可以这样做:
Assert.Throws(typeof<System.Exception>, TestDelegate (a)) |> ignore
附带说明一下,您可能想尝试 FsUnit 一个基于 NUnit 的更友好的框架。代码如下所示:
(fun () -> a() |> ignore)
|> should throw typeof<System.Exception>
在
Assert.Throws(fun () -> a() |> ignore)
ignore
适用于您正在测试的函数,不适用于 Assert.Throws
。这无疑是您的意图并且是正确的。
但是,Assert.Throws
- 与大多数 nunit 断言不同 - 实际上 return 是一个值:抛出的异常。你也可以忽略它...
Assert.Throws(fun () -> a() |> ignore) |> ignore
但是,通常您不想忽略 return。 returning 的全部意义在于你可能想要验证消息,查看堆栈跟踪等。如果我不想做任何事情,只是断言抛出了一些异常,我通常会使用
Assert.That(fun () -> a() |> ignore, Throws.Exception);
Assert.That returns C# 无效,又名 unit
.
[所有这些都是论坛代码,因为我没有在这台机器上安装 F#。 YMMV.]
假设我有这个代码:
let a () =
failwith "I want to fail!"
然后我有一个 nUnit 测试:
Assert.Throws(fun () -> a() |> ignore)
测试将 return:
Method has non-void return value, but no result is expected Exception doesn't have a stacktrace
如何测试出现预期故障情况的用例?
有几个关于异常的问题/答案,但我没有找到 failwith 案例的答案。
你可以这样做:
Assert.Throws(typeof<System.Exception>, TestDelegate (a)) |> ignore
附带说明一下,您可能想尝试 FsUnit 一个基于 NUnit 的更友好的框架。代码如下所示:
(fun () -> a() |> ignore)
|> should throw typeof<System.Exception>
在
Assert.Throws(fun () -> a() |> ignore)
ignore
适用于您正在测试的函数,不适用于 Assert.Throws
。这无疑是您的意图并且是正确的。
但是,Assert.Throws
- 与大多数 nunit 断言不同 - 实际上 return 是一个值:抛出的异常。你也可以忽略它...
Assert.Throws(fun () -> a() |> ignore) |> ignore
但是,通常您不想忽略 return。 returning 的全部意义在于你可能想要验证消息,查看堆栈跟踪等。如果我不想做任何事情,只是断言抛出了一些异常,我通常会使用
Assert.That(fun () -> a() |> ignore, Throws.Exception);
Assert.That returns C# 无效,又名 unit
.
[所有这些都是论坛代码,因为我没有在这台机器上安装 F#。 YMMV.]