paullesiak/golang-tests icon
public
Published on 5/29/2025
Golang Testing

Write test cases using table driven tests and testify/require

Rules

Testing Guidelines

  • Always use table driven tests when writing unit tests. These make it much simpler to test multiple parameters and arguments, as well as re-use test cases for maximum coverage

An example table driven test:

package main

import ( "testing" )

func TestTLog(t *testing.T) { t.Parallel() tests := []struct { name string }{ {"test 1"}, {"test 2"}, {"test 3"}, {"test 4"}, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { t.Parallel() t.Log(tt.name) }) } }

  • Always use testify/require for performing validation/assertion logic in test cases.

An example of using testify/require:

import ( "testing" "github.com/stretchr/testify/require" )

func TestSomething(t *testing.T) {

var a string = "Hello" var b string = "Hello"

require.Equal(t, a, b, "The two words should be the same.")

}