Table tests
One test, many cases. The name of the case is visible in the output when exactly that case fails.
A test is a function TestXxx(t *testing.T) in a file _test.go. The test package can be store or store_test. The second form sees only the export and checks the package the way foreign code sees it. The first sees the insides and belongs when you are testing unexported behavior.
Identical cases are not copied as functions. They are put in a table:
cases := []struct {
name string
in []int
want int
}{
{name: "нечётная", in: []int{3, 1, 2}, want: 2},
{name: "пустая", in: nil, want: 0},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
if got := Median(tc.in); got != tc.want {
t.Fatalf("%s: got %d want %d", tc.name, got, tc.want)
}
})
}
t.Run gives a subtest. If one fails, its name is in the output, and the others still run. t.Fatal stops the current subtest. t.Error records the failure and goes on. For comparing slices do not write your own loop if slices.Equal is enough.
A test must be deterministic. No time.Now() without a seam, and no map order. Test data lives nearby, not in a global variable that a previous test could have spoiled.
A failing message says what arrived and what was expected. t.Fatal("wrong") forces you to open a debugger. got and want in the text save that trip.
Practice
What t.Run is for
What does
t.Rungive you in a table test?- An operating-system process in parallel for each case
- A named subtest that can be found in the output
- Automatic generation of Want from the code
- Turning off the race detector
A median
Write
Median(nums []int) intas if a table test covers it. An empty input gives 0. Otherwise return the median of a sorted copy: for an odd length the middle element, for an even length the average of the two central ones, rounded down. Do not spoil the input slice variable.Fatal and Error
How does
t.Fataldiffer fromt.Error?- Fatal stops the current test, Error only records the failure
- Error stops the process, Fatal does not
- There is no difference
- Fatal is needed only in main