Go Testing

Go Built-in Unit Testing

Naming conventions ( prefix with underscore)

suffix with underscore with the filename. For example, the hello.go is the source file then hello.go with test package will have the filename hello_test.go tells the go test command that this file contains test functions.


Testing package

Importing the testing package is a must to be included along with other imported packages such as the “fmt” package that it commonly in use.

import (

Test command

At the command line where the source code directory, run the go test command to execute the test

go test

Implement a Test Functions

Expect results of the function

Prefix the Test to the function name. For example, TestHelloName()

// TestHelloName calls greetings.Hello with a name, checking 
// for a valid return value.
func TestHelloName(t *testing.T) {
    name := "Gladys"
    want := regexp.MustCompile(`\b`+name+`\b`)
    msg, err := Hello("Gladys")
    if !want.MatchString(msg) || err != nil {
        t.Fatalf(`Hello("Gladys") = %q, %v, want match for %#q, nil`, msg, err, want)



Unit Testing In GO