[英]F# - How to test an exception raised in the constructor with fsunit?
我想检查传递给类型构造函数的参数是否有效。
我检查它并在无效时引发ArgumentException 。
我想为此行为创建一个测试。 我想用Assert.throws或最好FSUnit,而不是一个try /方框。
#package "FsUnit@3.4.1"
#package "nunit@3.11.0"
open System
open FSUnit
type configuration = {aaa:int}
type Client(conf:configuration) =
do
if conf.aaa < 3 then raise (ArgumentException("aaa must be at least 3"))
member this.do_something() =
()
// 测试
// 1. does not "compile"
Assert.Throws<ArgumentException>(fun () -> Client(configuration) |> ignore)
// 2. does not work
//Assert.Throws<ArgumentException>( fun () ->
// let a = Client(configuration);
// a
// |> ignore)
// 3. does not work
(fun() -> Client(configuration)) |> ignore |> should throw typeof<ArgumentException>
// 4. OK but... bleah!
try
Client(configuration) |> ignore
Assert.Fail()
with
| :? ArgumentException -> Assert.Pass() |> ignore
| _ -> Assert.Fail()
你的第一种方法对我来说很好 - 我只需要定义不包含在你的问题中的configuration
,但大概是在你的实际文件中的某个地方定义的。 以下编译和行为符合我的预期:
let configuration = { aaa = 1 }
Assert.Throws<ArgumentException>(fun () -> Client(configuration) |> ignore)
你的第二个代码片段不起作用,因为它ignore
在错误的地方-你是忽略了整个函数(其中包含要测试的代码),然后您传递unit
的断言。 ignore
调用需要在函数内部,以便它忽略调用构造函数的结果。 以下对我有用:
(fun() -> Client(configuration) |> ignore) |> should throw typeof<ArgumentException>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.