Golang Testing & Unit Test Quiz

Golang
0 Passed
0% acceptance

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.

40 Questions
~80 minutes
1

Question 1

What is the basic structure of a Go test?

go
func TestAdd(t *testing.T) {
    result := Add(2, 3)
    if result != 5 {
        t.Errorf("Add(2, 3) = %d; want 5", result)
    }
}
A
Function named TestXxx taking *testing.T parameter
B
Any function with test in name
C
Class with test methods
D
No specific structure
2

Question 2

How do you run Go tests?

bash
go test                    # Run tests in current package
go test ./...             # Run tests recursively
go test -v                # Verbose output
go test -run TestAdd      # Run specific test
A
Use go test command with various flags
B
Use go run
C
Use go build
D
Cannot run tests
3

Question 3

What is table-driven testing?

go
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)
            }
        })
    }
}
A
Testing with tables of test cases using struct slices and subtests
B
Testing with databases
C
Testing with files
D
No table-driven testing
4

Question 4

How do you skip a test?

go
func TestSlowOperation(t *testing.T) {
    if testing.Short() {
        t.Skip("Skipping slow test in short mode")
    }
    // Slow test code
}
A
Use t.Skip() or check testing.Short()
B
Use return
C
Use panic
D
Cannot skip tests
5

Question 5

What is a benchmark in Go?

go
func BenchmarkAdd(b *testing.B) {
    for i := 0; i < b.N; i++ {
        Add(1, 2)
    }
}
A
Function named BenchmarkXxx that measures performance
B
Unit test
C
Integration test
D
No benchmarks in Go
6

Question 6

How do you write assertions in Go tests?

go
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)
    }
}
A
Use if statements with t.Error/t.Errorf/t.Fatal
B
Use assert.Equal
C
Use require.True
D
No assertions in Go
7

Question 7

What is test coverage?

bash
go test -cover              # Show coverage percentage
go test -coverprofile=c.out  # Generate coverage profile
go tool cover -html=c.out    # View coverage in browser
A
Percentage of code lines executed during tests
B
Number of tests
C
Test execution time
D
No coverage in Go
8

Question 8

How do you test error conditions?

go
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)
    }
}
A
Check that error is returned and has correct type/message
B
Ignore errors
C
Use panic
D
Cannot test errors
9

Question 9

What is a subtest?

go
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")
        }
    })
}
A
Nested test created with t.Run() for organizing test cases
B
Separate test file
C
Benchmark
D
No subtests in Go
10

Question 10

How do you benchmark memory allocations?

go
func BenchmarkConcat(b *testing.B) {
    b.ReportAllocs()
    
    for i := 0; i < b.N; i++ {
        s := "hello" + "world"  // Allocates
    }
}
A
Use b.ReportAllocs() to measure memory allocations
B
Use runtime.MemStats
C
Use pprof
D
Cannot measure allocations
11

Question 11

What is the testing.T type?

go
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
}
A
Type passed to test functions for logging, errors, and control
B
Timer
C
Test runner
D
No testing.T
12

Question 12

How do you test concurrent code?

go
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)
    }
}
A
Use goroutines in tests with synchronization primitives
B
Cannot test concurrent code
C
Use time.Sleep
D
Use channels only
13

Question 13

What is the difference between t.Error and t.Fatal?

go
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")
}
A
t.Error logs failure and continues, t.Fatal logs and stops test
B
No difference
C
t.Fatal is for errors
D
No t.Fatal
14

Question 14

How do you use test helpers?

go
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)
}
A
Create helper functions with t.Helper() to improve error reporting
B
Use global functions
C
Use macros
D
No helpers in Go
15

Question 15

What is benchmark comparison?

bash
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/op
A
Comparing performance of different implementations
B
Comparing test results
C
Comparing coverage
D
No comparison in Go
16

Question 16

How do you test HTTP handlers?

go
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)
    }
}
A
Use httptest.NewRecorder and httptest.NewRequest
B
Start real HTTP server
C
Use curl
D
Cannot test HTTP handlers
17

Question 17

What is fuzz testing in Go?

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)
        }
    })
}
A
Automated test generation with random inputs
B
Manual test writing
C
Benchmarking
D
No fuzz testing in Go
18

Question 18

How do you organize test files?

go
// 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
}
A
Use _test.go suffix, group related tests, use build tags for integration tests
B
One big test file
C
Test in main files
D
No organization needed
19

Question 19

What is the testing.B type?

go
func BenchmarkSort(b *testing.B) {
    data := make([]int, 1000)
    
    b.ResetTimer()  // Start timing here
    for i := 0; i < b.N; i++ {
        sort.Ints(data)
    }
}
A
Type passed to benchmark functions for control and timing
B
Test type
C
Timer
D
No testing.B
20

Question 20

How do you test with timeouts?

go
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")
    }
}
A
Use select with time.After for test timeouts
B
Use t.Timeout
C
Use time.Sleep
D
Cannot test timeouts
21

Question 21

What is test parallelization?

go
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
}
A
Running tests concurrently with t.Parallel()
B
Running tests sequentially
C
Running benchmarks
D
No parallelization
22

Question 22

How do you mock dependencies in tests?

go
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
}
A
Use interfaces and create mock implementations
B
Use reflection
C
Use global variables
D
Cannot mock in Go
23

Question 23

What is benchmark baseline?

go
func BenchmarkOld(b *testing.B) {
    // Old implementation
}

func BenchmarkNew(b *testing.B) {
    // New implementation
}

// Run: go test -bench=. -benchmem
// Compare results to see improvement
A
Comparing benchmark results to measure performance changes
B
Test baseline
C
Coverage baseline
D
No baseline in Go
24

Question 24

How do you test file I/O?

go
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)
    }
}
A
Use temporary files and clean up after tests
B
Use real files
C
Use in-memory buffers
D
Cannot test file I/O
25

Question 25

What is test coverage analysis?

bash
go test -coverprofile=coverage.out
go tool cover -html=coverage.out  # View in browser
go tool cover -func=coverage.out   # Text summary
A
Analyzing which code lines are executed during tests
B
Analyzing test speed
C
Analyzing memory usage
D
No coverage analysis
26

Question 26

How do you test panics?

go
func TestPanic(t *testing.T) {
    defer func() {
        if r := recover(); r == nil {
            t.Error("Expected panic")
        }
    }()
    
    mustPanic()  // This should panic
}
A
Use recover() in defer to catch expected panics
B
Use try/catch
C
Cannot test panics
D
Use t.Panic
27

Question 27

What is benchmark setup/cleanup?

go
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)
    }
}
A
Setup expensive data outside timing loop, use b.ResetTimer()
B
Setup inside loop
C
No setup/cleanup
D
Use defer in loop
28

Question 28

How do you test race conditions?

go
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 -race
A
Use go test -race to detect data races
B
Use manual checking
C
Use time.Sleep
D
Cannot test races
29

Question 29

What is integration testing in Go?

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")
    }
}
A
Testing with real dependencies using build tags
B
Unit testing
C
Benchmarking
D
No integration testing
30

Question 30

How do you benchmark suboperations?

go
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()
        }
    })
}
A
Use b.Run() to benchmark individual parts separately
B
Use separate functions
C
Use time.Now()
D
Cannot benchmark parts
31

Question 31

What is test fixture?

go
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
}
A
Setup code that prepares test environment
B
Test data
C
Test framework
D
No fixtures in Go
32

Question 32

How do you test time-dependent code?

go
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()
}
A
Inject time dependencies or use dependency injection for time
B
Use time.Sleep
C
Use real time
D
Cannot test time code
33

Question 33

What is benchmark statistical analysis?

bash
go test -bench=. -count=10 -benchtime=2s

// Output includes statistical analysis:
// BenchmarkSort-8    2000000    1234 ns/op ± 5%
A
Running benchmarks multiple times for statistical significance
B
Single run analysis
C
Test analysis
D
No statistics
34

Question 34

How do you test command-line applications?

go
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)
    }
}
A
Use exec.Command to run binary and check output
B
Use fmt.Scanf
C
Use os.Args
D
Cannot test CLI apps
35

Question 35

What is test-driven development (TDD) in Go?

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 passing
A
Writing tests first, then implementing code to pass tests
B
Writing code first
C
Writing tests last
D
No TDD in Go
36

Question 36

How do you test with context?

go
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)
    }
}
A
Pass context to functions and test timeout/cancellation behavior
B
Ignore context
C
Use time.Sleep
D
Cannot test context
37

Question 37

What is benchmark profiling?

bash
go test -bench=. -cpuprofile=cpu.prof

go tool pprof cpu.prof

// In pprof: top, web, etc.
A
Creating CPU/memory profiles during benchmark runs
B
Test profiling
C
Coverage profiling
D
No profiling
38

Question 38

How do you test database interactions?

go
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")
    }
}
A
Use test database with setup/cleanup for each test
B
Use production database
C
Use global database
D
Cannot test database
39

Question 39

What is continuous testing?

bash
go test -short ./...  # Run fast tests on every change

// Use tools like:
// - gotestsum for better output
// - richgo for colored output
// - watch for automatic re-running
A
Running tests frequently during development
B
Running tests once
C
Running benchmarks
D
No continuous testing
40

Question 40

What is the most important testing principle in Go?

A
Write tests that are fast, reliable, maintainable; use table-driven tests; test error conditions; achieve good coverage; use go test -race
B
Write many tests
C
Write slow tests
D
Skip testing

QUIZZES IN Golang