【问题标题】:fsunit.xunit test exception in constructor构造函数中的 fsunit.xunit 测试异常
【发布时间】:2014-05-27 09:03:18
【问题描述】:

拥有

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

我正在尝试使用 FsUnit + xUnit 测试此异常:

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

但是当它运行时我看到XUnit.MatchException。 我做错了什么?

  1. Test source code
  2. Category type source code

【问题讨论】:

    标签: f# xunit fsunit guard-clause


    【解决方案1】:

    虽然我不是 FsUnit 专家,但我认为 MatchException 类型是预期的,因为 FsUnit 使用自定义匹配器,并且匹配不成功。

    但是,所写的测试似乎不正确,因为

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

    是一个签名为unit -&gt; Category的函数,但你并不真正关心返回的Category

    相反,你可以写成

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

    注意添加的ignore 关键字,它忽略了Category 返回值。此测试通过,如果您删除 Guard Clause,则测试失败。

    【讨论】:

    • github.com/fsprojects/FsUnit/issues/14 如果您下载源代码并在 Windows 上构建它,一些围绕异常测试的单元测试会失败。我只是在学习 F#,所以我无法解决问题。
    • 哦,亲爱的,感谢您的链接...我很确定上面的代码在我尝试时有效,而且我也在运行 Windows...这就是我问的原因。这可能是临时出现的问题。无论如何,我不使用 FsUnit,因为我发现 Unquote 好多了。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-29
    • 1970-01-01
    • 1970-01-01
    • 2023-04-07
    • 1970-01-01
    相关资源
    最近更新 更多