GO Testing and Benchmarking 2 — Questions and Answers
Question 1: What is a table-driven test in Go?
- Tests generated from a SQL table
- A test that loops over a slice of input/output pairs to cover many cases in one function (Correct answer)
- A test formatted in a table file
- A benchmark that records results in a table
Correct answer: A test that loops over a slice of input/output pairs to cover many cases in one function
Table-driven tests define a slice of structs with inputs and expected outputs, then loop over them with `t.Run` subtests for clear, concise coverage.
Question 2: What does `t.Run(name, func)` provide in Go testing?
- Runs a test in a separate process
- Creates a named subtest that can be run independently and appears in test output (Correct answer)
- Runs a function concurrently with the test
- Registers a cleanup function
Correct answer: Creates a named subtest that can be run independently and appears in test output
`t.Run` creates a named subtest, enabling structured test output, independent `-run` filtering, and parallel subtests via `t.Parallel()`.
Question 3: How do you write a benchmark function in Go?
- Name it starting with `Bench` and take `*testing.B`
- Name it starting with `Benchmark` and take `*testing.B` (Correct answer)
- Name it starting with `Perf` and take `*testing.T`
- Use `//go:benchmark` directive
Correct answer: Name it starting with `Benchmark` and take `*testing.B`
Benchmark functions follow `BenchmarkXxx(b *testing.B)` naming convention and are run with `go test -bench=.`.
Question 4: What is the significance of `b.N` in a Go benchmark?
- The number of goroutines to use
- The target benchmark duration in nanoseconds
- The number of iterations the benchmark function should execute its inner loop (Correct answer)
- The number of CPUs to use
Correct answer: The number of iterations the benchmark function should execute its inner loop
`b.N` is automatically adjusted by the benchmark framework until the benchmark runs long enough to produce a stable measurement; your loop must iterate `b.N` times.
Question 5: What does `go test -cover` report?
- List of covered test files
- The percentage of statements executed during tests (Correct answer)
- The number of tests passing
- Dependencies covered by tests
Correct answer: The percentage of statements executed during tests
`go test -cover` reports the percentage of Go source statements that were executed during the test run, giving a code coverage metric.
Question 6: Which function registers a cleanup callback in Go tests?
- t.Defer()
- t.Cleanup() (Correct answer)
- defer t.Close()
- t.Teardown()
Correct answer: t.Cleanup()
`t.Cleanup(func())` registers a function to be called when the test and all its subtests complete, similar to `defer` but scoped to the test lifetime.
What is a table-driven test in Go?