Skip to content

Go Test Subtest

DodaTech 1 min read

In this tutorial, you'll learn about Go Test: Subtest Organization. We cover key concepts, practical examples, and best practices.

Subtest organization -- Use t.Run() to group related assertions into named subtests for better test output and control.

The Problem

Subtests allow you to organize complex tests into steps, run subsets with go test -run, and execute independently.

Wrong

func TestUserCRUD(t *testing.T) {
    // Create test
    user := createUser(t)
    // Read test
    found := readUser(t, user.ID)
    // Update test
    updated := updateUser(t, user.ID)
    // Delete test
    deleteUser(t, user.ID)
    // If any line fails, rest is skipped
}

Output:

// Sequential. Create failure blocks all others.
func TestUserCRUD(t *testing.T) {
    user := createUser(t)
    t.Run("read", func(t *testing.T) {
        found, err := readUser(user.ID)
        if found.Name != user.Name { t.Error(...) }
    })
    t.Run("update", func(t *testing.T) {
        updated, err := updateUser(user.ID)
        if updated.Name != "new" { t.Error(...) }
    })
    t.Run("delete", func(t *testing.T) {
        err := deleteUser(user.ID)
        if err != nil { t.Error(...) }
    })
}

Output:

// Independent subtest execution with clear naming

Prevention

  • Use t.Run("name", func(t *testing.T) { ... }) for subtests
  • Subtests run sequentially within the parent
  • Use t.Parallel() for parallel subtests
  • go test -run TestUserCRUD/read runs single subtest
  • Subtests share parent setup

Common Mistakes with test subtest

  1. Forgetting that lazy evaluation defers computation until the value is forced, causing space leaks with unevaluated thunks
  2. Using return to exit a function early instead of wrapping a pure value in the monad
  3. Mixing let bindings with <- bindings in do notation, producing type errors

These mistakes appear frequently in real-world GO code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.

Practice Exercise

Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.

This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.

FAQ

**Can subtests be parallel?**

Yes. Call t.Parallel() inside the subtest function.

How to run specific subtest?

go test -run TestName/SubtestName.

Do subtests share test state?

Yes, unless explicitly isolated.


Built by the developers of Doda Browser, DodaZIP, and Durga Antivirus Pro. DodaTech tutorials help Go developers build production-ready software used by millions.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro