Tests in Go

Learn some of the test features in Go, including subtests, table-driven tests, and flags.

Go has some fantastic features for tests that are worth mentioning.

Subtests

Subtests help us write more structured test code. Let’s use an example to understand this:

Press + to interact
package subtests
import (
"fmt"
)
type Person struct {
age int
}
func NewPerson(age int) (*Person, error) {
if age < 0 {
return nil, fmt.Errorf("age cannot be less than 0")
}
return &Person{age: age}, nil
}

For the rest of the lesson, we’ll rely on this production function for writing tests. The NewPerson function has two branches to cover:

  • The happy one is when we provide a valid age.
  • The bad one is when we pass an invalid age.

With that being said, we have to write two test functions that we’ll call TestNewPerson_WithValidAge and TestNewPerson_WithNotValidAge. ...