« Back to Index

[Go Unit Table Test Example]

View original Gist on GitHub

Tags: #go #golang #tests #testing #unittest #parallel #async #table #matrix

0. Parallel Example.go

// Explanation of `tc := tc` https://gist.github.com/posener/92a55c4cd441fc5e5e85f27bca008721

for _, tc := range testCases {
    tc := tc // necessary to avoid closure issues where last iteration data is used for all parallel tests
    t.Run(tc.Name, func(t *testing.T) {
        t.Parallel()
      
      	// execute code and assert behaviour
    })
}

1. Code.go

// Split slices s into all substrings separated by sep and
// returns a slice of the substrings between those separators.
func Split(s, sep string) []string {
    var result []string
    i := strings.Index(s, sep)
    for i > -1 {
        result = append(result, s[:i])
        s = s[i+len(sep):]
        i = strings.Index(s, sep)
    }
    return append(result, s)
}

2. Test.go

func TestSplit(t *testing.T) {
    tests := map[string]struct {
        input string
        sep   string
        want  []string
    }{
        "simple":       {input: "a/b/c", sep: "/", want: []string{"a", "b", "c"}},
        "wrong sep":    {input: "a/b/c", sep: ",", want: []string{"a/b/c"}},
        "no sep":       {input: "abc", sep: "/", want: []string{"abc"}},
        "trailing sep": {input: "a/b/c/", sep: "/", want: []string{"a", "b", "c"}},
    }

    for name, tc := range tests {
        t.Run(name, func(t *testing.T) {
            got := Split(tc.input, tc.sep)
            if !reflect.DeepEqual(tc.want, got) {
                t.Fatalf("expected: %v, got: %v", tc.want, got)
            }
        })
    }
}

/*
When comparing values using reflect.DeepEqual we could opt for %#v for more code structured output,
but that doesn't always work, so we can instead use https://github.com/google/go-cmp

For example:

func main() {
    type T struct {
        I int
    }
    x := []*T{{1}, {2}, {3}}
    y := []*T{{1}, {2}, {4}}
    fmt.Println(cmp.Equal(x, y)) // false
}
*/

3. Test Failure Output.sh

% go test
--- FAIL: TestSplit (0.00s)
    --- FAIL: TestSplit/trailing_sep (0.00s)
        split_test.go:25: expected: [a b c], got: [a b c ]

4. Run Specific Test.sh

% go test -run=.*/trailing -v
=== RUN   TestSplit
=== RUN   TestSplit/trailing_sep
--- FAIL: TestSplit (0.00s)
    --- FAIL: TestSplit/trailing_sep (0.00s)
        split_test.go:25: expected: [a b c], got: [a b c ]