简体   繁体   中英

How to visualize struct differences in golang unit tests

It's easy to compare (flat) structs in golang and it's pretty common to have unit tests that verify equality of structs. Now, I'd like to provide developers with proper feedback what exactly went wrong. I know I could implement VisualizeStructDifference somehow, but I'd be surprised if it hasn't been done before. I'd be even surprised if it wasn't easily accessible from golangs standard testing tools.

Can you give me some pointers?

An example:

func TestStruct(t *testing.T) {
    cases := []struct {
        name  string
        input InputStruct
        want  OutputStruct
    }{
        {
            name: "Case A",
            input: InputStruct{
                A: "Input A",
                B: "Input B",
            },
            want: OutputStruct{
                One: "Output One",
                Two: "Output Two",
            },
        },
        // ...
    }
    for _, tc := range cases {
        t.Run(tc.name, func(t *testing.T) {
            result := unitUnderTest(tc.input)
            
            if result != tc.want{
                t.Errorf("Test %v failed: %v", tc.name, VisualizeStructDifference(result, tc.want))
            }
        }
    }
}

I found a solution for my use case: stretchr/testify provides

assert.EqualValuesf(t, tc.want, result, "%v failed", tc.name)

Output:

Diff:
                                --- Expected
                                +++ Actual
                                @@ -3,3 +3,3 @@
                                  One: (string) (len=10) "Output One",
                                - Two: (string) (len=10) "Output Two",
                                + Two: (string) (len=9) "Output Tw",

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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