Question

Having

type Category(name : string, categoryType : CategoryType) = 
        do
            if (name.Length = 0) then
                invalidArg "name" "name is empty"

i'm trying to test this exception using FsUnit + xUnit:

[<Fact>]
let ``name should not be empty``() =
    (fun () -> Category(String.Empty, CategoryType.Terminal)) |> should throw typeof<ArgumentException>

but when it runs I see XUnit.MatchException. What i'm doing wrong?

  1. Test source code
  2. Category type source code
Was it helpful?

Solution

While I'm not an FsUnit expert, I think the MatchException type is expected, because FsUnit uses custom matchers, and the match doesn't succeed.

However, the test, as written, seems to be incorrect, because

(fun () -> Category(String.Empty, CategoryType.Terminal)

is a function with the signature unit -> Category, but you don't really care about the returned Category.

Instead, you can write it as

[<Fact>]
let ``name should not be empty``() =
    (fun () -> Category(String.Empty, CategoryType.Terminal) |> ignore)
    |> should throw typeof<ArgumentException>

Notice the added ignore keyword, which ignores the Category return value. This test passes, and fails if you remove the Guard Clause.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top