liveBook · Manning

TestXxx function

As explained in Learn Go with Pocket-Sized Projects

A TestXxx function is a Go test function whose name begins with Test and whose parameter is a pointer to testing.T.

A TestXxx function is a Go test function named with the Test<FunctionName> pattern and declared with a *testing.T parameter. It calls a function, compares the result with an expected value, and reports failures through testing.T. section 2.1.4

Structure each test around four phases:

  • Preparation: set up inputs, expected outputs, environment variables, connections, or other required state. section 2.1.4
  • Execution: call the function being tested, usually in a single line. section 2.1.4
  • Decision: compare the result or state with the desired value and mark mismatches as failures. section 2.1.4
  • Teardown: restore or remove altered state, often with defer. section 2.1.4

Testing greet

func TestGreet(t *testing.T) { want := "Hello world" got := greet() if got != want { t.Errorf("expected: %q, got: %q", want, got) } } section 2.1.4

Listing 2.4 main_internal_test.go: Testing greet
package main

import "testing"

func TestGreet(t *testing.T) {
    want := "Hello world"

    got := greet()

    if got != want {
        // mark this test as failed
        t.Errorf("expected: %q, got: %q", want, got)
    }
}

Browse the complete TestGreet test, including its testing import, expected value, function call, comparison, and failure report. section 2.1.4

How Learn Go with Pocket-Sized Projects covers it

How deep it goes
Defines the signature and four-phase workflow, while deferring the reasons for using a pointer to testing.T.
Examples
Demonstrates TestGreet by comparing greet's returned string with the expected "Hello world" value.
What it assumes
Assumes familiarity with Go functions and comparisons while teaching the TestXxx signature and test phases.
What you can do after
Apply the testing package to write a function test and report mismatches with t.Errorf.
How it connects
Connects testing.T with the testing package, Example functions, defer, and function result comparisons.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Learn Go with Pocket-Sized Projects. The section links point to the parts of the book it draws on.