CodeBlanks Logo Icon CodeBlanks

t.Error and t.Fatal

Learn t.Error and t.Fatal to report failures.

t.Error and t.Fatal

t.Error / t.Errorf mark the test as failed but keep running, so several failures show up in the same test. t.Fatal / t.Fatalf mark it failed and stop the test immediately.

f, err := os.Open("veri.txt")
if err != nil {
    t.Fatalf("açılamadı: %v", err)  // no point continuing
}
if got := satirSay(f); got != 3 {
    t.Errorf("satır = %d, beklenen 3", got)
}

A good failure message

Go convention: what was called, what came back, what was expected — the "got/want" format:

t.Errorf("Parse(%q) = %v, want %v", girdi, got, want)

Fatal must not be called inside a goroutine; it only works in the goroutine running the test (because it uses runtime.Goexit). Pass errors from goroutines back to the main test with a channel.

Practice got/want message

Pretend you forgot to implement Buyut(s string) string: it returns s unchanged. For got := Buyut("go") and want := "GO", print the message fmt.Printf("Buyut(%q) = %q, want %q\n", ...).

Starter code

main.go
package main

import "fmt"

func main() {
    // buraya yaz
}

Sample solution

main.go
package main

import "fmt"

func Buyut(s string) string { return s }

func main() {
    got, want := Buyut("go"), "GO"
    if got != want {
        fmt.Printf("Buyut(%q) = %q, want %q\n", "go", got, want)
    }
}

Expected output

Buyut("go") = "go", want "GO"

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 When is t.Fatal preferred?

  • When later steps depend on the previous result (e.g. the file failed to open) Correct answer
  • Always
  • Never
  • Only in benchmarks

Explanation: Use Fatal when continuing would cause a nil pointer error or meaningless extra failures; for independent checks Error is enough.

2 Stop the test

Question
if err != nil {
    t.____("kurulum başarısız: %v", err)
}
Answer
if err != nil {
    t.Fatalf("kurulum başarısız: %v", err)
}

Explanation: Fatalf writes the error and ends the test immediately.

3 Method and behavior

Term Meaning
t.Error Fail, continue
t.Fatal Fail, stop
t.Log Just a note
t.Skip Skip the test

All lessons in Intermediate