3

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
Guy Coder
  • 24,501
  • 8
  • 71
  • 136
Dzmitry Martavoi
  • 6,867
  • 6
  • 38
  • 59

1 Answers1

4

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.

Mark Seemann
  • 225,310
  • 48
  • 427
  • 736
  • 1
    https://github.com/fsprojects/FsUnit/issues/14 If you download the source code and build it on windows, some unit tests surrounding exception testing fail. I'm just learning F# so I can't resolve the issue. – Razor Dec 24 '14 at 04:09
  • 1
    Oh, dear, thanks for the link... I'm pretty sure the above code worked when I tried it, and I'm running Windows as well... That's the reason I asked. It may be an issue that's come up in the interim. Anyway, I don't use FsUnit, since I find [Unquote](https://code.google.com/p/unquote) much better. – Mark Seemann Dec 24 '14 at 12:39