Golang Testing & Unit Test Quiz
40 comprehensive questions on Golang's testing framework, covering the testing package, writing unit tests, table-driven tests, benchmarks with go test -bench, and test coverage tools — with 20 code examples demonstrating testing best practices.
Question 1
What is the basic structure of a Go test?
func TestAdd(t *testing.T) {
result := Add(2, 3)
if result != 5 {
t.Errorf("Add(2, 3) = %d; want 5", result)
}
}Question 2
How do you run Go tests?
go test # Run tests in current package
go test ./... # Run tests recursively
go test -v # Verbose output
go test -run TestAdd # Run specific testQuestion 3
What is table-driven testing?
func TestAdd(t *testing.T) {
tests := []struct {
name string
a, b int
expected int
}{
{"positive", 2, 3, 5},
{"negative", -1, 1, 0},
{"zero", 0, 0, 0},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
result := Add(tt.a, tt.b)
if result != tt.expected {
t.Errorf("got %d, want %d", result, tt.expected)
}
})
}
}Question 4
How do you skip a test?
func TestSlowOperation(t *testing.T) {
if testing.Short() {
t.Skip("Skipping slow test in short mode")
}
// Slow test code
}Question 5
What is a benchmark in Go?
func BenchmarkAdd(b *testing.B) {
for i := 0; i < b.N; i++ {
Add(1, 2)
}
}Question 6
How do you write assertions in Go tests?
func TestDivide(t *testing.T) {
result, err := Divide(10, 2)
if err != nil {
t.Fatal("unexpected error:", err)
}
if result != 5 {
t.Errorf("Divide(10, 2) = %d; want 5", result)
}
}Question 7
What is test coverage?
go test -cover # Show coverage percentage
go test -coverprofile=c.out # Generate coverage profile
go tool cover -html=c.out # View coverage in browserQuestion 8
How do you test error conditions?
func TestDivideByZero(t *testing.T) {
_, err := Divide(10, 0)
if err == nil {
t.Error("expected error for division by zero")
}
// Check error type
if _, ok := err.(*DivideByZeroError); !ok {
t.Errorf("wrong error type: %T", err)
}
}Question 9
What is a subtest?
func TestAdd(t *testing.T) {
t.Run("positive", func(t *testing.T) {
if Add(2, 3) != 5 {
t.Error("failed")
}
})
t.Run("negative", func(t *testing.T) {
if Add(-1, 1) != 0 {
t.Error("failed")
}
})
}Question 10
How do you benchmark memory allocations?
func BenchmarkConcat(b *testing.B) {
b.ReportAllocs()
for i := 0; i < b.N; i++ {
s := "hello" + "world" // Allocates
}
}Question 11
What is the testing.T type?
func TestExample(t *testing.T) {
t.Log("This is a log message")
t.Error("This is an error")
t.Fatal("This stops the test")
// Code here won't execute
}Question 12
How do you test concurrent code?
func TestConcurrentCounter(t *testing.T) {
var counter int64
var wg sync.WaitGroup
for i := 0; i < 100; i++ {
wg.Add(1)
go func() {
defer wg.Done()
atomic.AddInt64(&counter, 1)
}()
}
wg.Wait()
if counter != 100 {
t.Errorf("counter = %d; want 100", counter)
}
}Question 13
What is the difference between t.Error and t.Fatal?
func TestMultiple(t *testing.T) {
if check1() != expected1 {
t.Error("check1 failed") // Continues
}
if check2() != expected2 {
t.Fatal("check2 failed") // Stops here
}
// This won't execute if t.Fatal was called
t.Log("All checks passed")
}Question 14
How do you use test helpers?
func assertEqual(t *testing.T, got, want int) {
t.Helper()
if got != want {
t.Errorf("got %d, want %d", got, want)
}
}
func TestAdd(t *testing.T) {
assertEqual(t, Add(2, 3), 5)
assertEqual(t, Add(1, 1), 2)
}Question 15
What is benchmark comparison?
go test -bench=. -benchmem -count=3
// Output shows:
// BenchmarkOld-8 1000000 1234 ns/op 48 B/op 2 allocs/op
// BenchmarkNew-8 1000000 1156 ns/op 32 B/op 1 allocs/opQuestion 16
How do you test HTTP handlers?
func TestHandler(t *testing.T) {
req := httptest.NewRequest("GET", "/", nil)
w := httptest.NewRecorder()
handler(w, req)
if w.Code != http.StatusOK {
t.Errorf("got status %d, want %d", w.Code, http.StatusOK)
}
expected := "Hello World"
if w.Body.String() != expected {
t.Errorf("got body %q, want %q", w.Body.String(), expected)
}
}Question 17
What is fuzz testing in Go?
func FuzzReverse(f *testing.F) {
f.Add("hello")
f.Add("world")
f.Fuzz(func(t *testing.T, s string) {
reversed := Reverse(s)
doubleReversed := Reverse(reversed)
if doubleReversed != s {
t.Errorf("Double reverse failed: %q", s)
}
})
}Question 18
How do you organize test files?
// add_test.go - tests for add.go
// server_test.go - tests for server.go
// integration_test.go - integration tests
// Build tags for integration tests:
// +build integration
func TestIntegration(t *testing.T) {
// Integration test code
}Question 19
What is the testing.B type?
func BenchmarkSort(b *testing.B) {
data := make([]int, 1000)
b.ResetTimer() // Start timing here
for i := 0; i < b.N; i++ {
sort.Ints(data)
}
}Question 20
How do you test with timeouts?
func TestSlowOperation(t *testing.T) {
done := make(chan bool)
go func() {
slowOperation()
done <- true
}()
select {
case <-done:
// Success
case <-time.After(5 * time.Second):
t.Fatal("Operation timed out")
}
}Question 21
What is test parallelization?
func TestParallel1(t *testing.T) {
t.Parallel()
// This test runs in parallel with others
}
func TestParallel2(t *testing.T) {
t.Parallel()
// Also runs in parallel
}Question 22
How do you mock dependencies in tests?
type Database interface {
GetUser(id int) (*User, error)
}
// Mock implementation
type mockDB struct{}
func (m *mockDB) GetUser(id int) (*User, error) {
if id == 1 {
return &User{Name: "Alice"}, nil
}
return nil, errors.New("not found")
}
func TestService(t *testing.T) {
db := &mockDB{}
service := NewService(db)
// Test with mock
}Question 23
What is benchmark baseline?
func BenchmarkOld(b *testing.B) {
// Old implementation
}
func BenchmarkNew(b *testing.B) {
// New implementation
}
// Run: go test -bench=. -benchmem
// Compare results to see improvementQuestion 24
How do you test file I/O?
func TestReadFile(t *testing.T) {
// Create temp file
tmpfile, err := ioutil.TempFile("", "test")
if err != nil {
t.Fatal(err)
}
defer os.Remove(tmpfile.Name())
// Write test data
testData := "hello world"
if _, err := tmpfile.WriteString(testData); err != nil {
t.Fatal(err)
}
tmpfile.Close()
// Test reading
data, err := ReadFile(tmpfile.Name())
if err != nil {
t.Fatal(err)
}
if data != testData {
t.Errorf("got %q, want %q", data, testData)
}
}Question 25
What is test coverage analysis?
go test -coverprofile=coverage.out
go tool cover -html=coverage.out # View in browser
go tool cover -func=coverage.out # Text summaryQuestion 26
How do you test panics?
func TestPanic(t *testing.T) {
defer func() {
if r := recover(); r == nil {
t.Error("Expected panic")
}
}()
mustPanic() // This should panic
}Question 27
What is benchmark setup/cleanup?
func BenchmarkHeavy(b *testing.B) {
data := setupExpensiveData() // Setup once
defer cleanupData(data) // Cleanup once
b.ResetTimer() // Start timing
for i := 0; i < b.N; i++ {
process(data)
}
}Question 28
How do you test race conditions?
func TestRace(t *testing.T) {
var counter int
var wg sync.WaitGroup
for i := 0; i < 100; i++ {
wg.Add(1)
go func() {
defer wg.Done()
counter++ // Race condition
}()
}
wg.Wait()
// May not be 100 due to race
}
// Run with: go test -raceQuestion 29
What is integration testing in Go?
// +build integration
func TestDatabaseConnection(t *testing.T) {
db := connectToRealDatabase()
defer db.Close()
// Test real database operations
user, err := db.GetUser(1)
if err != nil {
t.Fatal(err)
}
if user.Name != "Alice" {
t.Error("Wrong user")
}
}Question 30
How do you benchmark suboperations?
func BenchmarkComplex(b *testing.B) {
b.Run("part1", func(b *testing.B) {
for i := 0; i < b.N; i++ {
part1()
}
})
b.Run("part2", func(b *testing.B) {
for i := 0; i < b.N; i++ {
part2()
}
})
}Question 31
What is test fixture?
func setupTestDB(t *testing.T) *sql.DB {
db, err := sql.Open("sqlite3", ":memory:")
if err != nil {
t.Fatal(err)
}
// Setup schema and data
_, err = db.Exec(`CREATE TABLE users (id INTEGER, name TEXT)`)
if err != nil {
t.Fatal(err)
}
return db
}
func TestUserService(t *testing.T) {
db := setupTestDB(t)
defer db.Close()
service := NewUserService(db)
// Test service
}Question 32
How do you test time-dependent code?
func TestScheduler(t *testing.T) {
scheduler := NewScheduler()
// Mock time
now := time.Now()
scheduler.now = func() time.Time { return now }
scheduler.Schedule(now.Add(time.Hour), func() {
t.Log("Task executed")
})
// Advance time
scheduler.now = func() time.Time { return now.Add(time.Hour) }
scheduler.RunPending()
}Question 33
What is benchmark statistical analysis?
go test -bench=. -count=10 -benchtime=2s
// Output includes statistical analysis:
// BenchmarkSort-8 2000000 1234 ns/op ± 5%Question 34
How do you test command-line applications?
func TestCLI(t *testing.T) {
cmd := exec.Command("./myapp", "--input", "test.txt")
output, err := cmd.CombinedOutput()
if err != nil {
t.Fatal(err)
}
expected := "Processed test.txt"
if string(output) != expected {
t.Errorf("got %q, want %q", string(output), expected)
}
}Question 35
What is test-driven development (TDD) in Go?
// 1. Write failing test
func TestAdd(t *testing.T) {
if Add(2, 3) != 5 {
t.Error("Add failed")
}
}
// 2. Implement minimal code to pass
func Add(a, b int) int {
return a + b
}
// 3. Refactor while keeping tests passingQuestion 36
How do you test with context?
func TestWithContext(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
defer cancel()
result, err := doWork(ctx)
if err != nil {
if ctx.Err() == context.DeadlineExceeded {
t.Log("Operation timed out as expected")
} else {
t.Error("Unexpected error:", err)
}
} else {
t.Logf("Result: %v", result)
}
}Question 37
What is benchmark profiling?
go test -bench=. -cpuprofile=cpu.prof
go tool pprof cpu.prof
// In pprof: top, web, etc.Question 38
How do you test database interactions?
func TestUserRepository(t *testing.T) {
db := setupTestDB(t)
defer db.Close()
repo := NewUserRepository(db)
// Test Create
user := &User{Name: "Alice"}
err := repo.Create(user)
if err != nil {
t.Fatal(err)
}
// Test Get
retrieved, err := repo.Get(user.ID)
if err != nil {
t.Fatal(err)
}
if retrieved.Name != "Alice" {
t.Error("Wrong name")
}
}Question 39
What is continuous testing?
go test -short ./... # Run fast tests on every change
// Use tools like:
// - gotestsum for better output
// - richgo for colored output
// - watch for automatic re-runningQuestion 40
What is the most important testing principle in Go?
