CodeGym /행동 /Go SELF /Table-driven tests — cases, names, readable errors

Table-driven tests — cases, names, readable errors

Go SELF
레벨 29, 레슨 1
사용 가능

1. Why table tests are needed

If you are writing tests for the first time, the natural strategy is this: “well, I have three scenarios — I’ll write three tests.” That is normal. The problem appears a little later, when the number of scenarios grows to 10, 20, 50… and you suddenly discover that your tests are growing like a developer’s beard before a release: quickly, unevenly, and for some reason in the most inconvenient places.

Let’s imagine that in our educational application todo we have validation for a task title. While the requirements are still small, we can write tests “by hand”.

// title.go
package todo

import "errors"

var ErrEmptyTitle = errors.New("empty title")

func ValidateTitle(s string) error {
	if s == "" {
		return ErrEmptyTitle
	}
	return nil
}

And “manual” tests:

// title_test.go
package todo

import "testing"

func TestValidateTitle_OK(t *testing.T) {
	if err := ValidateTitle("read book"); err != nil {
		t.Fatalf("unexpected error: %v", err)
	}
}
package todo

import "testing"

func TestValidateTitle_Empty(t *testing.T) {
	if err := ValidateTitle(""); err == nil {
		t.Fatalf("expected error, got nil")
	}
}

So far everything looks decent. But as soon as scenarios like " " (spaces only), a too-long title, forbidden characters, “a semicolon at the end because that’s how I feel” are added, you either start spawning clone tests or stop adding tests altogether (the second happens more often, but let’s pretend we did not see it).

And this is where the table-driven approach appears: cases become data, and the test becomes a “engine” that runs all cases in the same way.

2. How a table-driven test is structured

Cases as data in []struct{...}

A table-driven test in Go is a contract with yourself: “I describe scenarios compactly, and I write the repetitive checking mechanism only once.” Go is especially convenient here: you already know struct literals and slices, and for range too, so there is no magic.

Let’s start with the smallest “table”: input and whether an error is expected.

// title_test.go
package todo

import "testing"

func TestValidateTitle_Table(t *testing.T) {
	tests := []struct {
		in      string
		wantErr bool
	}{
		{in: "read book", wantErr: false},
		{in: "", wantErr: true},
	}

	for i, tt := range tests {
		err := ValidateTitle(tt.in)
		if tt.wantErr && err == nil {
			t.Errorf("case %d: ValidateTitle(%q): expected error, got nil", i, tt.in)
		}
		if !tt.wantErr && err != nil {
			t.Errorf("case %d: ValidateTitle(%q): unexpected error: %v", i, tt.in, err)
		}
	}
}

Pay attention to a couple of things.

First, []struct{...} is a type-safe table. You are not carrying around map[string]any and trying to remember what you put there and where you lost it. The fields of the struct are the “columns” of your table.

Second, we added case %d via the index i, because without that the error message often looks like “it does not work.” The index is the cheapest way to understand which scenario failed.

But the index is not the most readable, and next we will learn how to give cases names.

Case names: so errors read like a report

When a test fails, your goal is to understand in minimal time: which scenario broke and what exactly does not match. The index case 3 is better than nothing, but a week later you will look at it the same way you look at someone else’s code without comments: “who did this and why did no one warn me?”

So the next step is to add a name field and use it in messages. This is not subtests (we will not touch those yet), it is just a human label.

package todo

import "testing"

func TestValidateTitle_Table_Names(t *testing.T) {
	tests := []struct {
		name    string
		in      string
		wantErr bool
	}{
		{name: "ok", in: "read book", wantErr: false},
		{name: "empty", in: "", wantErr: true},
	}

	for _, tt := range tests {
		err := ValidateTitle(tt.in)
		if tt.wantErr && err == nil {
			t.Errorf("%s: ValidateTitle(%q): expected error, got nil", tt.name, tt.in)
		}
		if !tt.wantErr && err != nil {
			t.Errorf("%s: ValidateTitle(%q): unexpected error: %v", tt.name, tt.in, err)
		}
	}
}

Now if a test fails, you will see something like:

  • empty: ValidateTitle(""): expected error, got nil

And that already looks like a proper report.

A separate note about %q. For strings, it is almost always better than %s, because empty strings, spaces, and special characters become visible. In tests, this saves nerves.

Checking errors: wantErr and the meaning of the error

Errors in Go are values, and they are meant to be handled meaningfully: check err != nil, sometimes compare with a “known” error or search for it in a chain.

In a table-driven test, it is important not to mix two worlds: “an error is expected” and “no error is expected.” The most common beginner mistake is to keep checking the result even when the error is already “not the one.” Ideally the logic should read like this:

  1. If an error was expected — check that err != nil, and end the scenario there.
  2. If no error was expected — check that err == nil, and only then check the result.

Let’s make an example where we check the meaning of the error, not just the fact that it exists.

First let’s strengthen our validation: let it return different errors.

// title.go
package todo

import "errors"

var (
	ErrEmptyTitle   = errors.New("empty title")
	ErrTooLongTitle = errors.New("title too long")
)

func ValidateTitle(s string) error {
	if s == "" {
		return ErrEmptyTitle
	}
	if len(s) > 10 {
		return ErrTooLongTitle
	}
	return nil
}

Now the table-driven test may look like this:

// title_test.go
package todo

import (
	"errors"
	"testing"
)

func TestValidateTitle_Errors(t *testing.T) {
	tests := []struct {
		name string
		in   string
		want error
	}{
		{name: "ok", in: "read", want: nil},
		{name: "empty", in: "", want: ErrEmptyTitle},
		{name: "too_long", in: "read book now", want: ErrTooLongTitle},
	}

	for _, tt := range tests {
		err := ValidateTitle(tt.in)
		if !errors.Is(err, tt.want) {
			t.Errorf("%s: ValidateTitle(%q): err=%v, want %v", tt.name, tt.in, err, tt.want)
		}
	}
}

Why is this convenient?

If want == nil, then errors.Is(err, nil) will return true only when err == nil. In other words, one check covers both “there is no error” and “the error must be a specific one.” It becomes compact.

Why not compare error text? Because text is a UX detail. You can change the wording (“empty title” → “title is empty”), and the test will fail even though the logic did not break. Usually that is not what you want from a unit test.

A function like (int, error): got/want without extra noise

A very typical Go scenario is a function returning a value and an error. In our todo, this could be parsing a task priority from a string: in a CLI, in HTTP, in a file — anywhere.

Let’s make a simple function:

// priority.go
package todo

import (
	"fmt"
	"strconv"
)

func ParsePriority(s string) (int, error) {
	n, err := strconv.Atoi(s)
	if err != nil {
		return 0, fmt.Errorf("parse priority: %w", err)
	}
	if n < 0 {
		return 0, fmt.Errorf("priority must be >= 0")
	}
	return n, nil
}

Now the test. Here it is important: we do not want to compare the whole err “as a string”, but we do want to clearly separate scenarios. For an educational level, it is convenient to start with wantErr bool, and check values only when there should be no error.

// priority_test.go
package todo

import "testing"

func TestParsePriority_Table(t *testing.T) {
	tests := []struct {
		name    string
		in      string
		want    int
		wantErr bool
	}{
		{name: "zero", in: "0", want: 0, wantErr: false},
		{name: "positive", in: "5", want: 5, wantErr: false},
		{name: "negative", in: "-1", want: 0, wantErr: true},
		{name: "not_a_number", in: "x", want: 0, wantErr: true},
	}

	for _, tt := range tests {
		got, err := ParsePriority(tt.in)

		if tt.wantErr {
			if err == nil {
				t.Errorf("%s: ParsePriority(%q): expected error, got nil", tt.name, tt.in)
			}
			continue
		}

		if err != nil {
			t.Errorf("%s: ParsePriority(%q): unexpected error: %v", tt.name, tt.in, err)
			continue
		}

		if got != tt.want {
			t.Errorf("%s: ParsePriority(%q)=%d, want %d", tt.name, tt.in, got, tt.want)
		}
	}
}

Here the two continue statements are not “complexity for complexity’s sake,” but a way to make the report cleaner. If an unexpected error appears in a scenario, then comparing got with want is pointless: got may have been zero simply because that is what we agreed to return on error. Without continue, you can easily get a “double” error for one case, and the report becomes noisy.

Readable error messages: what to write in t.Errorf

A message in t.Errorf is not a formality. It is your debug log that appears exactly when everything is already bad, time is short, and the coffee is gone. A good message should answer three questions: “which case,” “which input,” and “what we got and what we expected.”

Let’s start with the general template “function(input)=got, want want”:

t.Errorf("%s: ParsePriority(%q)=%d, want %d", tt.name, tt.in, got, tt.want)

For errors, it is almost always useful to write unexpected error: %v and print the err itself, so you can see the context (for example, from fmt.Errorf("...: %w", err)).

t.Errorf("%s: ParsePriority(%q): unexpected error: %v", tt.name, tt.in, err)

Another small but important point: when you print strings, use %q. This is especially important for “empty” and “spaces.”

t.Errorf("%s: ValidateTitle(%q): expected error, got nil", tt.name, tt.in)

Finally, if there are several inputs in a case, print all of them. Seriously. You will not remember them “by case name” if there are 30 cases.

Mini example: building a todo task

To keep table-driven tests from being “tests for the sake of tests,” let’s connect them to a small piece of business logic. We have a task, and we have user input: a title and a priority as a string. It is convenient to have one function that does “read → parse → validate → build a struct.”

First, the model:

// task.go
package todo

type Task struct {
	Title    string
	Priority int
}

Now the build function:

// build.go
package todo

import "fmt"

func BuildTask(title, priorityStr string) (Task, error) {
	if err := ValidateTitle(title); err != nil {
		return Task{}, fmt.Errorf("title: %w", err)
	}
	p, err := ParsePriority(priorityStr)
	if err != nil {
		return Task{}, fmt.Errorf("priority: %w", err)
	}
	return Task{Title: title, Priority: p}, nil
}

And a table-driven test that checks both “success” and “error expected.” Here we will not insist on exact error types (we already wrap them), so we will keep the check at the level of “error should be / should not be,” and fully verify success.

// build_test.go
package todo

import "testing"

func TestBuildTask_Table(t *testing.T) {
	tests := []struct {
		name    string
		title   string
		prioStr string
		want    Task
		wantErr bool
	}{
		{name: "ok", title: "read", prioStr: "2", want: Task{Title: "read", Priority: 2}},
		{name: "bad_title", title: "", prioStr: "2", wantErr: true},
		{name: "bad_prio", title: "read", prioStr: "x", wantErr: true},
	}

	for _, tt := range tests {
		got, err := BuildTask(tt.title, tt.prioStr)

		if tt.wantErr {
			if err == nil {
				t.Errorf("%s: expected error, got nil", tt.name)
			}
			continue
		}

		if err != nil {
			t.Errorf("%s: unexpected error: %v", tt.name, err)
			continue
		}

		if got != tt.want {
			t.Errorf("%s: got=%v, want=%v", tt.name, got, tt.want)
		}
	}
}

Notice: we were able to compare Task with != because the struct contains only comparable fields (string and int). This is a very pleasant bonus for tests: got/want becomes easier to read.

And here is a small diagram of how the test “engine” works with the table:

flowchart TD
    A[Take case tt from tests] --> B[Call function: got, err]
    B --> C{tt.wantErr?}
    C -->|yes| D{err == nil?}
    D -->|yes| E[Error: expected error, got nil]
    D -->|no| F[Case passed]
    C -->|no| G{err != nil?}
    G -->|yes| H[Error: unexpected error]
    G -->|no| I{got == want?}
    I -->|no| J[Error: got vs want]
    I -->|yes| K[Case passed]

This logic is almost always the same. Once you get used to it, table-driven tests start being written very quickly.

3. Typical mistakes in table-driven tests

Mistake #1: do not add a case identifier to messages.
When a check fails in a loop, without name or at least case %d you get a message without context and are forced to guess manually which scenario it was. This is especially painful when inputs are similar. The fix is simple: always print tt.name or i.

Mistake #2: mix “error expected” and “no error expected” scenarios in one branch.
Beginners often compare got first, then check err, and sometimes even forget that when there is an error, got may be a “placeholder.” It is better to decide the fate of err first: if an error is expected — check it and leave the case; if not — make sure err == nil, and only then compare got with want.

Mistake #3: compare the error text as the main way of checking.
The error text can change without changing the meaning, especially if you add context through fmt.Errorf("...: %w", err). It is more stable to check “there is / is not an error,” and if you need to check the meaning — use a recognizable error (sentinel) and errors.Is, not err.Error() == "...".

Mistake #4: make “fat” cases with 15 fields.
When the case structure becomes huge, the test becomes hard to read: you no longer see what differs between scenarios. A good table-driven test usually contains only the fields that really participate in the scenario. If there are too many fields, that is a signal that you are testing too much logic at once and should simplify the function under test a bit or split the check.

Mistake #5: use t.Fatalf inside the loop and accidentally stop all the remaining cases.
Sometimes Fatal is appropriate, but in a table-driven test without running each case separately (while we are not using subtests yet), t.Fatalf will stop the whole test, and you will see only the first problem. More often you want to collect several failures in one run. That is why in a loop people usually use t.Errorf and continue, leaving Fatal for truly “impossible” situations.

1
과제
Go SELF, 레벨 29, 레슨 1
잠금
합계판
합계판
1
과제
Go SELF, 레벨 29, 레슨 1
잠금
범위 제한기
범위 제한기
1
과제
Go SELF, 레벨 29, 레슨 1
잠금
설문지의 나이
설문지의 나이
1
과제
Go SELF, 레벨 29, 레슨 1
잠금
사용자 이름 검증
사용자 이름 검증
코멘트
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION