Basic

  1. Create test file with name xxx_test.go where xxx is the name of the file you are testing
  1. Test functions
    1. import Testing
    1. must start with the key word Test
    1. must have a single parameter t *testing.T

Example

hello_test.go

package main

import "testing"

func TestHello(t *testing.T) {
	got := Hello()
	want := "Hello World"

	if got != want {
		t.Errorf("Got %q and want %q", got, want)
	}
}

Subtests

func TestHello(t *testing.T) {

	t.Run("When name is not empty, say 'Hello, name'", func(t *testing.T) {
		got := Hello("Ben")
		want := "Hello, Ben"
		assertCorrectMessage(t, want, got)
	})

	t.Run("When name is empty, say 'Hello, World'", func(t *testing.T) {
		got := Hello("")
		want := "Hello, World"
		assertCorrectMessage(t, want, got)
	})
}

func assertCorrectMessage(t testing.TB, want, got string) {
	// used so that when the test fails it shows that the method that called this
	// helper gets the failure line not this one 
	t.Helper() 

	if want != got {
		t.Errorf("Got %q and want %q", got, want)
	}
}

Test Cases

func TestArea(t *testing.T) {
	tests := []struct {
		name    string
		shape   Shape
		hasArea float64
	}{
		{name: "Circle", shape: Circle{Radius: 10}, hasArea: 314.1592653589793},
		{name: "Rectangle", shape: Rectangle{Width: 10, Height: 11}, hasArea: 110},
		{name: "Triangle", shape: Triangle{Height: 10, Width: 11}, hasArea: 55},
	}

	for _, test := range tests {
		t.Run(test.name, func(testing *testing.T) {
			got := test.shape.Area()

			if got != test.hasArea {
				testing.Errorf("Expected %.2f but got %.2f", test.hasArea, got)
			}
		})
	}
}