Unit Testing

⭐ Interview Importance: HIGH
⏱️ Revision Time: 4 min

TL;DR

Go doesn’t require third-party libraries like Jest or Mocha. The standard library includes a powerful testing package. You write tests in files ending with _test.go, and run them using the go test command.

Mental Model

How It Works

  1. Create a file named something_test.go in the same directory as the code you are testing.
  2. Inside the file, declare the same package name (package something).
  3. Write functions that start with the word Test followed by a capitalized word (e.g., TestCalculateTotal).
  4. The function must accept exactly one argument: t *testing.T.
  5. If the logic fails, call t.Errorf() to mark the test as failed but continue execution, or t.Fatalf() to fail and immediately stop the test.

Go does not have built-in assert.Equal() functions (though many teams use the popular github.com/stretchr/testify/assert library to add them). By default, you just use standard if statements.

Example

// --- math.go ---
package mathutil

func Add(a, b int) int {
	return a + b
}

// --- math_test.go ---
package mathutil

import "testing"

func TestAdd(t *testing.T) {
	// 1. Arrange
	a := 5
	b := 10
	expected := 15

	// 2. Act
	result := Add(a, b)

	// 3. Assert
	if result != expected {
		// This marks the test as FAILED and prints a formatted message
		t.Errorf("Add(%d, %d) returned %d; expected %d", a, b, result, expected)
	}
}

Running Tests:

  • Run all tests in the current folder: go test .
  • Run all tests in the entire project recursively: go test ./...
  • See verbose output (shows which tests passed/failed): go test -v ./...
  • Check code coverage: go test -cover ./...

Common Interview Questions

Can I test unexported (private) functions?

Yes! Because your _test.go file is in the exact same package as your source code (e.g., both are package utils), the test file has full access to all unexported variables and functions.

What is “Black Box” testing in Go?

Sometimes you explicitly don’t want your tests to access private functions. You want to test the package exactly as an external user would. To do this, you change the package name in your test file to package utils_test. This creates a strictly isolated test package. Now, your tests can only access the exported (capitalized) functions of the utils package. This ensures your public API is usable.