From charlesreid1

Revision as of 03:19, 13 December 2018 by Admin (talk | contribs)

Basics

How testing works in Go

For each file X.go a corresponding test named X_test.go should contain unit tests for that code.

To run tests, just use the built-in test command in go: go test

Example

Take this simple function as an example:

package main

import (
	"fmt"
)

// Return the square of a number
func square(x int) (result int) {
	return x * x
}

func main() {
	fmt.Println("Hello World")
}

We can write a corresponding test:

package main

import (
	"testing"
)

func test_square(t *testing.T) {
	if test_square(2) != 4 {
		t.Error("Error testing square(): did not return correct result")
	}
}

Resources

Introduction to testing in Go: https://tutorialedge.net/golang/intro-testing-in-go/

Advanced Go testing tutorial: https://tutorialedge.net/golang/advanced-go-testing-tutorial/


Flags