我想检查传递给类型的构造函数的参数是否有效。
如果无效,我将检查它并引发ArgumentException。
我想为这种行为创建一个测试。我想使用Assert.throws,或者最好使用FSUnit,而不是try/with块。
#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()发布于 2019-03-27 11:46:48
您的第一种方法对我来说很好--我只需要定义configuration,它没有包含在您的问题中,但大概是在实际文件中的某个位置定义的。以下是我所期望的编译和行为:
let configuration = { aaa = 1 }
Assert.Throws<ArgumentException>(fun () -> Client(configuration) |> ignore)第二个代码段无法工作,因为它将ignore放在错误的位置--您忽略了整个函数(它包含要测试的代码),然后将unit传递给断言。ignore调用需要在函数的内部,这样它就忽略了调用构造函数的结果。以下几点对我来说是可行的:
(fun() -> Client(configuration) |> ignore) |> should throw typeof<ArgumentException>https://stackoverflow.com/questions/55367481
复制相似问题