【问题标题】:F# - How to test an exception raised in the constructor with fsunit?F# - 如何使用 fsunit 测试构造函数中引发的异常?
【发布时间】:2019-03-26 23:09:08
【问题描述】:

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

【问题讨论】:

    标签: f# fsunit


    【解决方案1】:

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

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

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

    (fun() -> Client(configuration) |> ignore) |> should throw typeof<ArgumentException>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-06-16
      • 1970-01-01
      • 2014-05-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-10-02
      • 1970-01-01
      相关资源
      最近更新 更多