[英]F# - How to test an exception raised in the constructor with fsunit?
I want to check if an argument passed to the constructor of a type is valid.我想检查传递给类型构造函数的参数是否有效。
I check it and raise an ArgumentException if not valid.我检查它并在无效时引发ArgumentException 。
I want to create a test for this behavior.我想为此行为创建一个测试。 I want to use Assert.throws or preferably FSUnit instead of a try/with block.我想用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() =
()
// TEST // 测试
// 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()
Your first approach works fine for me - I just had to define configuration
which is not included in your question but, presumably, is defined somewhere in your actual file.你的第一种方法对我来说很好 - 我只需要定义不包含在你的问题中的configuration
,但大概是在你的实际文件中的某个地方定义的。 The following compiles and behaves as expected for me:以下编译和行为符合我的预期:
let configuration = { aaa = 1 }
Assert.Throws<ArgumentException>(fun () -> Client(configuration) |> ignore)
Your second code snippet does not work because it has ignore
in the wrong place - you are ignoring the entire function (which contains the code that you want to test) and then you are passing unit
to the assertion.你的第二个代码片段不起作用,因为它ignore
在错误的地方-你是忽略了整个函数(其中包含要测试的代码),然后您传递unit
的断言。 The ignore
call needs to be inside of the function so that it ignores the result of calling the constructor. ignore
调用需要在函数内部,以便它忽略调用构造函数的结果。 The following works for me:以下对我有用:
(fun() -> Client(configuration) |> ignore) |> should throw typeof<ArgumentException>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.