How to visualize struct differences in golang unit tests

Viewed 42

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))
            }
        }
    }
}
1 Answers

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",
Related