简体   繁体   English

fsunit.xunit在构造函数中测试异常

[英]fsunit.xunit test exception in constructor

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: 我正在尝试使用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 . 但是当它运行时我看到XUnit.MatchException What i'm doing wrong? 我做错了什么?

  1. Test source code 测试源代码
  2. Category type source code 类别类型源代码

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. 虽然我不是FsUnit专家,但我认为MatchException类型是预期的,因为FsUnit使用自定义匹配器,并且匹配不成功。

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 . 是一个具有签名unit -> Category的函数,但您并不真正关心返回的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. 请注意添加的ignore关键字,它忽略Category返回值。 This test passes, and fails if you remove the Guard Clause. 此测试通过,如果您删除Guard子句则失败。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM