【问题标题】:Asserting exception in FsUnit F# for XUnit在 FsUnit F# for XUnit 中断言异常
【发布时间】:2017-01-12 20:59:39
【问题描述】:

我试图断言抛出了异常。这是重现问题的一段代码:

open FsUnit
open Xunit

let testException () =
    raise <| Exception()

[<Fact>]
let ``should assert throw correctly``() =
    (testException ())
        |> should throw typeof<System.Exception>

错误表明抛出了 System.Exception,但测试应该通过,因为这就是我所断言的。有人可以帮忙解决我哪里出错了。

【问题讨论】:

    标签: f# fsunit


    【解决方案1】:

    您正在调用testException 函数,然后将其结果作为参数传递给should 函数。在运行时,testException 崩溃,因此永远不会返回结果,因此永远不会调用 should 函数。

    如果您希望should 函数捕获并正确报告异常,您需要将testException 函数本身而不是其结果传递给它(因为首先没有结果)。这样,should 函数将能够在 try..with 块内调用 testException,从而捕获异常。

    testException |> should throw typeof<System.Exception>
    

    【讨论】:

    • 对我做错了什么有意义,但是我刚刚尝试过,现在我得到一个 MatchException,上面写着 Expected: System.Exception, Actual: was "SqlJuxtFunctionalTests.Tests.TableBuilder.PrimaryKeyTests +在尝试构建具有引用可空列@116的聚集主键的表时应该抛出异常“我相信这是我的函数的名称,所以感觉整个函数都与异常匹配,函数不是执行
    • 我认为您可能歪曲了您的问题。你的函数的签名是什么?你到底是如何通过的?请出示您的实际代码。
    • testException 函数的签名为 unit->a' 代码为:let testException () = raise &lt;| System.Exception() [&lt;Fact&gt;] let ``should assert throw correctly``() = testException |&gt; should throw typeof&lt;System.Exception&gt;
    【解决方案2】:

    这似乎可以解决问题:

    [<Fact>]
    let ``should assert throw correctly``() =
        (fun () -> Exception() |> raise |> ignore)
            |> should throw typeof<System.Exception>
    

    不太清楚为什么需要忽略。找不到任何可以解释这一点的东西。

    【讨论】:

      猜你喜欢
      • 2017-12-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多