Unit Testing
Purpose
Produce unit tests that actually catch regressions: fast, isolated, deterministic, and
complete over error paths and edge cases — not just the happy path. The skill encodes
the discovery taxonomy for edge cases, the required test structure per language, and
the performance-test hooks (benchmarks, fuzzing, race detection).
When to Use / When NOT to Use
Use when:
- Writing tests for new or changed functions ("write tests for this function").
- A bug was fixed and a regression test is required.
- Reviewing whether a test suite meaningfully covers behavior.
Do NOT use when:
- The question is which tests belong at which layer (integration/E2E) — use
testing/test-strategy.
- You need coverage measurement and thresholds — use
testing/test-coverage.
- The code is not yet designed for testability; refactor seams first
(
code-quality/refactoring).
Prerequisites & Assumptions
- Go: standard library only —
testing, reflect, sync (preserved legacy rule;
no assertion libraries), go test -race available.
- Java: JUnit 5 + AssertJ; Python:
pytest + unittest.mock.
- Tests run in seconds, no network/database/filesystem dependencies — collaborators
are injected interfaces faked in the test.
Step-by-Step Workflow
- Enumerate cases before writing code — cover the five discovery dimensions:
(1) boundary values (zero, min, max, ±1, overflow, NaN/Inf, empty, nil),
(2) concurrency and timing (races, cancellation mid-operation, deadline expiry),
(3) domain-specific real-world failures (≥5 production scenarios for core logic),
(4) input mutation and aliasing (caller mutates a passed slice/map),
(5) error paths (every unhandled or swallowed branch, partial failures).
- Name tests by behavior — Go
TestCancel_ExpiredOrder, Java
cancel_expiredOrder_throws, Python test_cancel_expired_order_raises.
- Write table-driven cases — one case table per function; each row: name, input,
want, wantErr. See example below.
- Test error contracts — assert with
errors.Is (Go), exception types + message
(JUnit), pytest.raises matchers — never assert only "returned an error".
- Add the performance hooks — a
Benchmark*/@Benchmark/pytest-benchmark for
hot paths and a fuzz target for parsers (go test -fuzz, JUnit jqwik, hypothesis).
- Verify — run the suite with race detector/strict warnings; confirm each new
test fails when the implementation is broken (mutate once, watch it fail).
Enterprise Rules & Standards (MUST / MUST NOT)
- MUST use table-driven/subtest structure for functions with >2 input scenarios.
- MUST cover every error branch and every boundary of the function under test.
- MUST keep tests deterministic: freeze time, seed randomness, no real network;
flaky tests are quarantined with an issue within 24h (see
test-strategy).
- MUST test concurrent code with the race detector enabled (
go test -race);
untested concurrency is unshipped concurrency.
- MUST give a bug fix a regression test in the same change.
- SHOULD share assertion helpers through one
helpers_test.go/fixture module
(assertEqual, assertErrorIs, requireNoError) instead of hand-rolled checks.
- SHOULD keep each test under ~40 lines; extract builders for long arrangements.
- MUST NOT test through mocks of the thing under test; mock only injected
collaborators at their interfaces.
- MUST NOT write tests that pass regardless of implementation (assert-on-mock
theater); assert observable outputs and state.
- MUST NOT use
time.Sleep for synchronization — use channels, sync
primitives, or awaitables.
Examples
Good — table-driven Go test with error contract (compiles, stdlib only):
func TestParseRetry(t *testing.T) {
tests := []struct {
name string
in string
want RetryPolicy
wantErr bool
}{
{name: "valid never", in: "never", want: RetryNever},
{name: "valid always", in: "always", want: RetryAlways},
{name: "empty string", in: "", wantErr: true},
{name: "unknown value", in: "sometimes", wantErr: true},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
t.Parallel()
got, err := parseRetry(RetryPolicy(tt.in))
if tt.wantErr {
if err == nil {
t.Fatalf("parseRetry(%q) = %v, want error", tt.in, got)
}
return
}
if err != nil {
t.Fatalf("parseRetry(%q) unexpected error: %v", tt.in, err)
}
if got != tt.want {
t.Errorf("parseRetry(%q) = %v, want %v", tt.in, got, tt.want)
}
})
}
}
Bad — testing only the happy path:
func TestParseRetry(t *testing.T) {
p, _ := parseRetry("always") // ignores the error value
if p != RetryAlways {
t.Fatal("wrong")
}
}
Why it fails: the blank error hides regressions in error handling, and one input
proves almost nothing about a parser.
Checklist
Common Pitfalls
- Coverage theater — tests that execute lines but assert nothing; every test
must assert an outcome.
- Test interdependence — shared mutable fixtures across tests; build fresh state
per test.
- Mock proliferation — mocking value types and pure functions; mock only I/O
collaborators.
- Assertion libraries as a crutch (Go) — the stdlib rule keeps builds lean; the
helper file gives the ergonomics.
References
1---2name: unit-testing3description: 'Writes fast, isolated unit tests — table-driven cases, error paths, edge-case discovery, concurrency tests, benchmarks, and fuzzing — using each language''s standard test stack. Trigger with "write tests for this function", "increase coverage", or "this bug needs a regression test".'4metadata:5 source: https://skillmd.com/skills/pnguyen215/unit-testing6---78# Unit Testing910## Purpose1112Produce unit tests that actually catch regressions: fast, isolated, deterministic, and13complete over error paths and edge cases — not just the happy path. The skill encodes14the discovery taxonomy for edge cases, the required test structure per language, and15the performance-test hooks (benchmarks, fuzzing, race detection).1617## When to Use / When NOT to Use1819Use when:2021- Writing tests for new or changed functions ("write tests for this function").22- A bug was fixed and a regression test is required.23- Reviewing whether a test suite meaningfully covers behavior.2425Do NOT use when:2627- The question is which tests belong at which layer (integration/E2E) — use28 `testing/test-strategy`.29- You need coverage measurement and thresholds — use `testing/test-coverage`.30- The code is not yet designed for testability; refactor seams first31 (`code-quality/refactoring`).3233## Prerequisites & Assumptions3435- Go: standard library only — `testing`, `reflect`, `sync` (preserved legacy rule;36 no assertion libraries), `go test -race` available.37- Java: JUnit 5 + AssertJ; Python: `pytest` + `unittest.mock`.38- Tests run in seconds, no network/database/filesystem dependencies — collaborators39 are injected interfaces faked in the test.4041## Step-by-Step Workflow42431. **Enumerate cases before writing code** — cover the five discovery dimensions:44 (1) boundary values (zero, min, max, ±1, overflow, NaN/Inf, empty, nil),45 (2) concurrency and timing (races, cancellation mid-operation, deadline expiry),46 (3) domain-specific real-world failures (≥5 production scenarios for core logic),47 (4) input mutation and aliasing (caller mutates a passed slice/map),48 (5) error paths (every unhandled or swallowed branch, partial failures).492. **Name tests by behavior** — Go `TestCancel_ExpiredOrder`, Java50 `cancel_expiredOrder_throws`, Python `test_cancel_expired_order_raises`.513. **Write table-driven cases** — one case table per function; each row: name, input,52 want, wantErr. See example below.534. **Test error contracts** — assert with `errors.Is` (Go), exception types + message54 (JUnit), `pytest.raises` matchers — never assert only "returned an error".555. **Add the performance hooks** — a `Benchmark*`/`@Benchmark`/`pytest-benchmark` for56 hot paths and a fuzz target for parsers (`go test -fuzz`, JUnit jqwik, hypothesis).576. **Verify** — run the suite with race detector/strict warnings; confirm each new58 test fails when the implementation is broken (mutate once, watch it fail).5960## Enterprise Rules & Standards (MUST / MUST NOT)6162- **MUST** use table-driven/subtest structure for functions with >2 input scenarios.63- **MUST** cover every error branch and every boundary of the function under test.64- **MUST** keep tests deterministic: freeze time, seed randomness, no real network;65 flaky tests are quarantined with an issue within 24h (see `test-strategy`).66- **MUST** test concurrent code with the race detector enabled (`go test -race`);67 untested concurrency is unshipped concurrency.68- **MUST** give a bug fix a regression test in the same change.69- **SHOULD** share assertion helpers through one `helpers_test.go`/fixture module70 (`assertEqual`, `assertErrorIs`, `requireNoError`) instead of hand-rolled checks.71- **SHOULD** keep each test under ~40 lines; extract builders for long arrangements.72- **MUST NOT** test through mocks of the thing under test; mock only injected73 collaborators at their interfaces.74- **MUST NOT** write tests that pass regardless of implementation (assert-on-mock75 theater); assert observable outputs and state.76- **MUST NOT** use `time.Sleep` for synchronization — use channels, sync77 primitives, or awaitables.7879## Examples8081Good — table-driven Go test with error contract (compiles, stdlib only):8283```go84func TestParseRetry(t *testing.T) {85 tests := []struct {86 name string87 in string88 want RetryPolicy89 wantErr bool90 }{91 {name: "valid never", in: "never", want: RetryNever},92 {name: "valid always", in: "always", want: RetryAlways},93 {name: "empty string", in: "", wantErr: true},94 {name: "unknown value", in: "sometimes", wantErr: true},95 }96 for _, tt := range tests {97 t.Run(tt.name, func(t *testing.T) {98 t.Parallel()99 got, err := parseRetry(RetryPolicy(tt.in))100 if tt.wantErr {101 if err == nil {102 t.Fatalf("parseRetry(%q) = %v, want error", tt.in, got)103 }104 return105 }106 if err != nil {107 t.Fatalf("parseRetry(%q) unexpected error: %v", tt.in, err)108 }109 if got != tt.want {110 t.Errorf("parseRetry(%q) = %v, want %v", tt.in, got, tt.want)111 }112 })113 }114}115```116117Bad — testing only the happy path:118119```go120func TestParseRetry(t *testing.T) {121 p, _ := parseRetry("always") // ignores the error value122 if p != RetryAlways {123 t.Fatal("wrong")124 }125}126```127128Why it fails: the blank error hides regressions in error handling, and one input129proves almost nothing about a parser.130131## Checklist132133- [ ] All five edge-case dimensions enumerated for the function under test.134- [ ] Table-driven structure with named cases; error cases assert error identity135 (`errors.Is` / exception type), not just presence.136- [ ] Regression test added for every bug fix in the change.137- [ ] Race detector (Go) or strict warnings (Java/Python) pass locally.138- [ ] Benchmarks exist for hot paths; fuzz target exists for parsers.139- [ ] No real network, filesystem, or sleeps in the test; suite runs in seconds.140141## Common Pitfalls142143- **Coverage theater** — tests that execute lines but assert nothing; every test144 must assert an outcome.145- **Test interdependence** — shared mutable fixtures across tests; build fresh state146 per test.147- **Mock proliferation** — mocking value types and pure functions; mock only I/O148 collaborators.149- **Assertion libraries as a crutch (Go)** — the stdlib rule keeps builds lean; the150 helper file gives the ergonomics.151152## References153154- testing package docs (Go): https://pkg.go.dev/testing155- Go fuzzing: https://go.dev/doc/fuzz156- JUnit 5 user guide: https://junit.org/junit5/docs/current/user-guide/157- pytest — parametrized tests: https://docs.pytest.org/en/stable/how-to/parametrize.html