简体   繁体   English

FsUnit.Xunit 列表应该包含一个 x 使得 fx

[英]FsUnit.Xunit list should contain an x such that f x

I am not sure how to write my test in FsUnit.Xunit .我不确定如何在FsUnit.Xunit中编写测试。

I want to check that at least one element in my list satisfies a predicate.我想检查列表中的至少一个元素是否满足谓词。 I know how to write this using should be True , but usually you can get better error messages by using the specialized functions.我知道如何使用should be True来编写它,但通常您可以通过使用专门的函数来获得更好的错误消息。

Hopefully this code makes it clear what I am trying to achieve:希望这段代码清楚地说明了我想要实现的目标:

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

I would do this:我会这样做:

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

Error output is useful:错误 output 很有用:

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

If you want more context, you can do this instead:如果你想要更多的上下文,你可以这样做:

open FsUnit.CustomMatchers

...

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

Error output is:错误 output 是:

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

The only downside of this approach is that the "Expected" message no longer displays the specific value you're looking for.这种方法的唯一缺点是“预期”消息不再显示您正在寻找的特定值。

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

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