Table-Driven Tests with Subtests and t.Run

Write table-driven Go tests that use subtests, parallel execution, and a shared example for email normalization cases.

GoData Integrity

Code

gosnippet
58 lines
package main

import (
	"fmt"
	"strings"
	"testing"
)

func normalizeEmail(raw string) (string, error) {
	email := strings.TrimSpace(strings.ToLower(raw))
	at := strings.IndexByte(email, '@')
	if at <= 0 || at == len(email)-1 || strings.Count(email, "@") != 1 {
		return "", fmt.Errorf("invalid email %q", raw)
	}
	return email, nil
}

func TestNormalizeEmail(t *testing.T) {
	t.Parallel()
	cases := []struct {
		name    string
		input   string
		want    string
		wantErr bool
	}{
		{"lowercases and trims", "  Ada@Example.COM ", "ada@example.com", false},
		{"rejects missing at", "ada.example.com", "", true},
		{"rejects empty local part", "@example.com", "", true},
		{"rejects double at", "ada@@example.com", "", true},
	}

	for _, testCase := range cases {
		testCase := testCase
		t.Run(testCase.name, func(t *testing.T) {
			t.Parallel()
			got, err := normalizeEmail(testCase.input)
			if testCase.wantErr {
				if err == nil {
					t.Fatalf("expected error, got %q", got)
				}
				return
			}
			if err != nil {
				t.Fatalf("unexpected error: %v", err)
			}
			if got != testCase.want {
				t.Fatalf("got %q, want %q", got, testCase.want)
			}
		})
	}
}

func ExampleNormalizeEmail() {
	email, _ := normalizeEmail("  Ada@Example.COM ")
	fmt.Println(email)
	// Output: ada@example.com
}

How it works

Count the functions normalizeEmail, TestNormalizeEmail and ExampleNormalizeEmail as the entire surface area of Table-Driven Tests with Subtests and t.Run.

The cycling part of this snippet is for _, testCase := range cases. Every fallible call checks err != nil (1 site), so an error is handled where it happens rather than bubbling invisibly.

What to watch for

  • Errors are ordinary return values; skipping the err check means using a zero value silently.

Applying it

Entry signature: func TestNormalizeEmail(t *testing.T)

TestNormalizeEmail is the public entry point; everything else in the file exists to support it.

Statements that matter

return "", fmt.Errorf("invalid email %q", raw)
func ExampleNormalizeEmail() {
email, _ := normalizeEmail("  Ada@Example.COM ")
fmt.Println(email)
// Output: ada@example.com
}
if err != nil {
t.Fatalf("unexpected error: %v", err)
}

Interactive Tools for This Topic

FAQ

What is the error handling style?
As returned `error` values, checked at its call site — callers must branch on `err` before using the other return values. No panics or exceptions in the snippet.
Is there an install step between copy and run?
No. Between copying and running there is nothing left to do. Every import resolves inside the standard library — `fmt`, `strings`, `testing`. The file defines `normalizeEmail`, `TestNormalizeEmail`, `ExampleNormalizeEmail` at load time.