Skip to main content

Two Ways to Fail

A test can report a problem in two ways, and the difference is what happens next:

t.Errorf marks the test as failed and keeps going. The rest of the test still runs, so one run can report several problems at once.

t.Fatalf marks the test as failed and stops it immediately. Use it when continuing makes no sense — the next lines would crash or produce noise.

Both have a plain twin without formatting: t.Error(...) and t.Fatal(...) just print their arguments.


t.Errorf: Report and Continue

When a test checks several cases in a row, t.Errorf is the right tool: a broken case is reported, and the following cases are still checked.

That way one go test run shows you the whole damage — not just the first broken case.

See every broken case at once

This Add ignores b, so all three checks fail. Because they use t.Errorf, all three messages appear in a single run — with t.Fatalf you would only see the first.

Prompt
Write a Go test file where Add has a bug (it returns only a, ignoring b) and TestAdd checks three different sums with t.Errorf so every broken case is reported. Show the go test -v output with all three failure messages in one run.
Output: Go test file and captured go test output

t.Fatalf: Stop at Once

Sometimes a failed check means the rest of the test cannot work. A typical case: the test first prepares a value, then inspects it. If the preparation already went wrong, inspecting would be useless or would even crash.

t.Fatalf stops the test right there. The checks after it never run — and that is the point.

Stop before the useless checks

Split has a bug (it splits on the wrong character), so 1 part comes back instead of 3. t.Fatalf reports it and stops — the check of the first part below is never reached.

Prompt
Write a Go test file where a Split function is supposed to split a comma-separated string but has a bug (splits on the wrong character). The test first checks the number of parts with t.Fatalf, then checks the first part with t.Errorf. Show the go test -v output where the fatal stops the test before the second check.
Output: Go test file and captured go test output
Stop before the useless checks

Error and Fatal Without Formatting

When you do not need %d or %q placeholders, use the plain forms: t.Error("message") and t.Fatal("message"). They behave exactly like their f twins — report and continue, or report and stop.

Plain messages

Two simple boolean checks with plain t.Error messages. Both pass here, so the messages stay silent and the run prints PASS.

Prompt
Write a Go test file with an IsEven function and a test that checks IsEven(4) is true and IsEven(3) is false using plain t.Error messages without formatting verbs. Show the passing go test -v output.
Output: Go test file and captured go test output
Plain messages