GO Testing and Benchmarking 1 — Questions and Answers
Question 1: What command runs all tests in the current Go module?
- go run tests
- go test ./... (Correct answer)
- go check ./...
- go verify ./...
Correct answer: go test ./...
`go test ./...` recursively runs all test files in the current module, with `./...` matching all packages.
Question 2: What naming convention must a Go test function follow?
- Must start with `Check`
- Must start with `Test` followed by a capital letter or underscore (Correct answer)
- Must end with `_test`
- Must be in a `_test.go` file only if it starts with `test_`
Correct answer: Must start with `Test` followed by a capital letter or underscore
Test functions must be named `TestXxx` where `Xxx` starts with an uppercase letter; they take a single `*testing.T` parameter.
Question 3: Which method on `*testing.T` marks a test as failed without stopping it?
- t.Fatal()
- t.Error() (Correct answer)
- t.Fail()
- t.Skip()
Correct answer: t.Error()
`t.Error()` logs the failure message and marks the test as failed but continues executing the rest of the test function, unlike `t.Fatal()` which stops immediately.
Question 4: What does `t.Fatal()` do in a Go test?
- Panics the test process
- Logs the message, marks the test as failed, and immediately stops the test function (Correct answer)
- Kills all running tests
- Marks the test as expected failure
Correct answer: Logs the message, marks the test as failed, and immediately stops the test function
`t.Fatal()` is equivalent to `t.Log()` followed by `t.FailNow()`, stopping the current test function immediately after logging the failure.
Question 5: What file suffix is required for Go test files?
- _spec.go
- _unit.go
- _test.go (Correct answer)
- .gotest
Correct answer: _test.go
Go test files must end with `_test.go`; the `go test` tool recognizes and compiles these files only during testing, not in regular builds.
Question 6: How do you run only a specific test function named `TestAdd`?
- go test -only TestAdd
- go test -run TestAdd (Correct answer)
- go test -func TestAdd
- go test TestAdd
Correct answer: go test -run TestAdd
`go test -run TestAdd` runs only test functions matching the regular expression `TestAdd`, enabling targeted test execution.
What command runs all tests in the current Go module?