typestar

Table-driven tests in Go

The Go house style: a slice of cases, one subtest each.

func Stars(tpm, target int) int {
    switch {
    case tpm >= target:
        return 3
    case tpm >= target*8/10:
        return 2
    default:
        return 1
    }
}

func TestStars(t *testing.T) {
    cases := []struct {
        name   string
        tpm    int
        target int
        want   int
    }{
        {"at the bar", 100, 100, 3},
        {"just under", 85, 100, 2},
        {"slow", 40, 100, 1},
    }

    for _, c := range cases {
        t.Run(c.name, func(t *testing.T) {
            if got := Stars(c.tpm, c.target); got != c.want {
                t.Errorf("Stars(%d, %d) = %d, want %d",
                    c.tpm, c.target, got, c.want)
            }
        })
    }
}

How it works

  1. Each case is a struct with a name and the data.
  2. t.Run gives every case its own name in the output.
  3. Adding a case is one line, not one function.

Keywords and builtins used here

The run, in numbers

Lines
32
Characters to type
501
Tokens
163
Three-star pace
100 tpm

At the three-star pace of 100 tokens a minute, this run takes about 98 seconds.

Type this snippet

Step 2 of 4 in Writing tests, step 2 of 13 in Testing.

← Previous Next →