Alex 75
Alex 75

Reputation: 3236

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.
I want to create a test for this behavior. I want to use Assert.throws or preferably FSUnit instead of a try/with block.

#package "[email protected]"
#package "[email protected]"

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()

Upvotes: 3

Views: 224

Answers (1)

Tomas Petricek
Tomas Petricek

Reputation: 243051

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. 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. The ignore call needs to be inside of the function so that it ignores the result of calling the constructor. The following works for me:

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

Upvotes: 2

Related Questions