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 "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() =
()
// 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()
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>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.