簡體   English   中英

F# - 如何使用 fsunit 測試構造函數中引發的異常?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM