liveBook · Manning

Test function

As explained in Go in Action, Second Edition

A test function is a Go function recognized by the testing tool as an executable test according to its required naming and signature convention.

A test function is a Go function that the go test tool recognizes by convention: it belongs in a *_test.go file, begins with Test, accepts a *testing.T parameter, and returns no value. The file is excluded from normal builds but compiled for testing. section 8.1 section 8.3

Use the test function to:

  • Arrange test data and expected results, act by calling the code under test, and assert the outcome. section 8.3
  • Report failures through the testing.T parameter, using messages that explain both the expectation and the actual result. section 8.3
  • Run automatically with go test; a test passes unless it times out, panics, or explicitly fails. section 8.2

Minimal executable test

In example_test.go, define: func TestPass(t *testing.T) { t.Log("This test will pass.") }. Running go test discovers the function and reports the package result; go test -v also displays its log and run status. section 8.2

Listing 8.4 An example test
func TestMyFeature(t *testing.T) {
	// 1. Define some test data.
	arg := "my data"

	// 2. Define an expected result.
	want := "expected value"

	// 3. Interact with your code and get some data.
	got := FunctionToTest(arg)

	// 4. Inspect the results.
	if got != want {
		// 5. Mark the test as failed, and log the reason why.
		t.Errorf("bad result - want: %v, got %v", want, got)
	}
}

Shows a complete test with input data, an expected value, a function call, comparison, and t.Errorf failure reporting. section 8.3

How Go in Action, Second Edition covers it

How deep it goes
Explains file placement, signature, discovery, failure reporting, and arrange-act-assert, but defers testing theory.
Examples
Demonstrates TestPass, FunctionToTest, expected-versus-actual comparison, t.Errorf, go test, and verbose output.
What it assumes
Assumes Go code to exercise and basic function usage while teaching the required test-file and function conventions.
What you can do after
Apply it via go test by writing discoverable functions that verify results and explain failures.
How it connects
Connects test functions with unit testing, arrange-act-assert, external test packages, benchmarks, fuzz tests, and examples.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Go in Action, Second Edition. The section links point to the parts of the book it draws on.