CodeBlanks Logo Icon CodeBlanks

Test function

Learn the func TestXxx signature and the go test command.

Test functions

In Go, tests are written in files ending with _test.go and run with go test. A test function starts with Test and takes a *testing.T:

// topla_test.go
package hesap

import "testing"

func TestTopla(t *testing.T) {
    if got := Topla(2, 3); got != 5 {
        t.Errorf("Topla(2, 3) = %d, beklenen 5", got)
    }
}

There is no separate test framework; the standard testing package is enough.

go test flags

Commonly used flags:

go test ./...            # all packages
go test -v -run TestTopla # verbose, tests matching the name
go test -race ./...      # data race detection
go test -cover ./...     # coverage
go test -count=1 ./...   # skip the cache

Tests can access the package's internal functions; to look from outside, use package hesap_test.

Practice Mini test runner

Imitate the essence of a test: write Topla(a, b int) int. In main, compute got := Topla(2, 3) and print "FAIL" if got != 5, otherwise "PASS".

Starter code

main.go
package main

import "fmt"

func main() {
    // buraya yaz
}

Sample solution

main.go
package main

import "fmt"

func Topla(a, b int) int { return a + b }

func main() {
    if got := Topla(2, 3); got != 5 {
        fmt.Println("FAIL")
        return
    }
    fmt.Println("PASS")
}

Expected output

PASS

Questions and answers

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

1 Which function does <code>go test</code> run as a test?

  • func TestToplam()
  • func TestToplam(t *testing.T) Correct answer
  • func testToplam(t *testing.T)
  • func Testtoplam(t *testing.T)

Explanation: The name must start with Test followed by an upper-case letter (or nothing), and the only parameter must be *testing.T.

2 Test file

Question
// topla____.go
package hesap
Answer
// topla_test.go
package hesap

Explanation: go test only builds and runs tests in files ending with _test.go.

3 Flag and effect

Term Meaning
-v Verbose output
-run Filter by name
-race Race detection
-cover Coverage

All lessons in Intermediate