Packages, modules and tooling · 3 MIN READ

Tests are a file, not a framework

Write a table-driven test and run it locally.

A test is a function such as func TestParse(t *testing.T) in a file ending _test.go. It can use the production package name, or a package name ending _test to exercise the exported API from outside the package.

A table-driven test keeps cases in data and the assertion in code. t.Run gives each case a separate name in the result stream. No external test framework is required.

SEE THE IDEA

A test is ordinary Go with a testing entry point

  1. 01

    File

    go
    parser_test.go

    Included by the test build

  2. 02

    Entry

    go
    func TestParse(t *testing.T)

    Names the behavior being tested

  3. 03

    Cases

    go
    t.Run(name, func(t *testing.T))

    Reports each named case separately

Production code and test code are compiled together according to the chosen test package.

In practice

Write tables around the observable contract: normal input, boundaries and failures. Use Fatal when continuing would make the rest of the test meaningless, and Error when collecting several independent mismatches is useful. Keep test data independent so adding a case does not change another case’s state.

Watch out

Tests in package name_test exercise the exported API; tests in the same package can also inspect unexported details.

Official reference ↗

Work through the exercise

go
package main

// Clamp returns value limited to the range low..high.
func Clamp(value, low, high int) int {
	return value
}

func main() {}
Try it yourself

Trace each value and write down your reasoning. Copy the source into GopherForge or your local Go environment to compile and check it. This web page does not execute your code or send it to a compiler service.

Progress stays in this browser. No account needed.