FsUnit `should equal` fails on `Some []`

社会主义新天地 提交于 2019-12-01 19:53:31
pad

The reason is that FsUnit uses untyped mechanism under the hood so Expected is inferred as object by the type checker (see the Object y part in the stacktrace).

A workaround is to add type annotation for generic values i.e.

[<Test>]
let test() =
  f []
  |> should equal (Some ([]: int list))

Several people have been bitten by this e.g. Weird None behaviour in type providers.

Beauty of fluent assertions is pointless to me once they're no longer type-safe. I suggest to create a type-safe alternative:

let shouldEqual (x: 'a) (y: 'a) = 
    Assert.AreEqual(x, y, sprintf "Expected: %A\nActual: %A" x y)

This is because your two empty lists are of different types. See the types of actual and expected in this version of your test:

[<Test>]
let test() =
  let expected = Some []
  let actual = f []
  actual |> should equal expected

expected is 'a list option and actual is int list option, so they are not equal.

If you give the compiler some hints about the expected result then it will work.

[<Test>]
let test() =
  f []
  |> should equal (Some List.empty<int>)
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!