f# – 如何为FsUnit提供有用的断言失败消息?

我正在使用FsUnit 2.3.2,我对失败消息不满意.请参阅以下示例:

[<Test>]
let ``test 1``() =
    [1; 3]
    |> should equal [1;2]

…给了我一个不那么有用的信息:

Expected and actual are both
Microsoft.FSharp.Collections.FSharpList`1[System.Int32]

at FsUnit.TopLevelOperators.should[a,a](FSharpFunc`2 f, a x, Object y)
in d:\GitHub\FsUnit\src\FsUnit.NUnit\FsUnit.fs:line 44 at Program.test
1() in F:\work\playground\fsunit\fsunit\Program.fs:line 9

我找到的解决方法是使用数组而不是列表:

[<Test>]
let ``test 2``() =
    [|1; 4|]
    |> should equal [|1;2|]

…产生

Expected and actual are both System.Int32[2]
Values differ at index [1]
Expected: 2
But was: 4

第二个问题是我是否定义了ADT

type MyT = 
    A of int 
    | B of string

[<Test>]
let ``test 4``() =
    A 10
    |> should equal (B "abc")

…给我的信息:

Expected: Program+MyT+B
But was: Program+MyT+A

…我可以通过为MyT实现ToString来解决这个问题:

override this.ToString() = match this with
    | A i -> sprintf "A(%d)" i
    | B s -> sprintf "B(%s)" s

…这会产生一个好消息:

Expected: B(abc)
But was: A(10)

…但是我希望fsunit能够以某种方式呈现MyT值(sprintf“%A”).

无论如何,不​​得不做这些变通办法.

如何在不使用数组的情况下获取F#列表的有用消息?

如何获取ADT的有用信息?

对于上述问题是否有一个很好的解决方法,或者我应该放弃FsUnit?

对于没有这些问题的F#单元测试库,你有更好的建议吗?

最佳答案 几个竞争者:

Expecto

[<Tests>]
let tests =
  testList "test group" [
    testCase "strings" <| fun _ ->
        let subject = "Hello World"
        Expect.equal subject "Hello world"
                    "The strings should be equal"

    testCase "lists" <| fun _ ->
        let expected = [1; 2]   
        Expect.equal expected [1; 3]
                    "The lists should be equal"

    testCase "DUs" <| fun _ ->
        let expected = A 10   
        Expect.equal expected (B "abc")
    ]

产量

06001

Unquote

[<Test>]
let ``The strings should be equal`` () =
    let subject = "Hello World"
    subject =! "Hello world"

06003

[<Test>]
let ``The lists should be equal`` () =
    let expected = [1; 2]
    expected =! [1; 3]

06005

[<Test>]
let ``The DUs should be equal`` () =
    let expected = A 10
    expected =! (B "abc")

06007

Unquote的好处在于它的报价,允许逐步失败的消息.

[<Test>]
let ``The arrays should be equal`` () =
    let expected = [|0 ; 2 ; 3 ; 4|]
    test <@ (Array.map ((+) 1) [|0 .. 3|]) = expected @>

06009

点赞