2

我想检查传递给类型构造函数的参数是否有效。如果无效 ,我会检查它并引发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()
4

1 回答 1

1

你的第一种方法对我来说很好 - 我只需要定义configuration你的问题中不包含的内容,但大概是在你的实际文件中的某个地方定义的。以下编译和行为符合我的预期:

let configuration = { aaa = 1 }
Assert.Throws<ArgumentException>(fun () -> Client(configuration) |> ignore)

您的第二个代码片段不起作用,因为它ignore位于错误的位置 - 您忽略了整个函数(其中包含您要测试的代码),然后您将传递unit给断言。ignore调用需要在函数内部,以便它忽略调用构造函数的结果。以下对我有用:

(fun() -> Client(configuration) |> ignore) |> should throw typeof<ArgumentException>
于 2019-03-27T11:46:48.743 回答