【问题标题】:FsUnit.Xunit list should contain an x such that f xFsUnit.Xunit 列表应该包含一个 x 使得 f x
【发布时间】:2021-05-11 22:30:10
【问题描述】:

我不确定如何在FsUnit.Xunit 中编写测试。

我想检查列表中的至少一个元素是否满足谓词。我知道如何使用should be True 编写此代码,但通常您可以使用专用函数获得更好的错误消息。

希望这段代码能清楚地说明我想要实现的目标:

open Xunit
open FsUnit.Xunit

type Foo = 
  {
    X : int
  }

[<Fact>]
let ``squares`` () =
  let xs =
    [ { X = 1 }; { X = 2 }; { X = 3 } ]
    |> List.map (fun foo -> { X = foo.X * foo.X })

  actual 
  |> should exists (satisfies (fun foo -> foo.X = 9)) // Not real code

【问题讨论】:

    标签: f# xunit fsunit


    【解决方案1】:

    我会这样做:

    xs
        |> Seq.map (fun foo -> foo.X)
        |> should contain 9
    

    错误输出很有用:

    Expected: Contains 8
    Actual:   seq [1; 4; 9]
    

    如果你想要更多的上下文,你可以这样做:

    open FsUnit.CustomMatchers
    
    ...
    
    xs |> should containf (fun foo -> foo.X = 9)
    

    错误输出是:

    Expected: Contains <fun:squares@21-1>
    Actual:   [{ X = 1 }; { X = 4 }; { X = 9 }]
    

    这种方法的唯一缺点是“预期”消息不再显示您正在寻找的特定值。

    【讨论】:

    • 不错的解决方案,尽管错误消息现在丢失了额外的上下文(想象Foo 包含更多成员)
    • 我想我找到了你想要的东西:FsUnit.CustomMatchers.containf。将相应地更新答案。
    • 我认为containf 是我们要做的最好的事情!
    • 我想使用 containf 但我没有 FSUnit.CustomMatchers。我正在使用 FsUnit 4.0.6 和 NUnit 3.13.2 。
    • 我认为CustomMatchers 适用于 xUnit,而不适用于 NUnit。
    猜你喜欢
    • 1970-01-01
    • 2020-11-18
    • 1970-01-01
    • 1970-01-01
    • 2019-04-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多