How to Write Tests for CLI Applications in Go

Test Go CLI apps by injecting arguments into os.Args and calling main() within a testing function.

Use the testing package to create a test file ending in _test.go and call testing.MainStart or testing.Main to execute your CLI's main function with specific arguments.

package main

import (
	"os"
	"testing"
)

func TestMain(t *testing.T) {
	// Simulate CLI arguments: go run mkzip.go zoneinfo.zip
	os.Args = []string{"mkzip.go", "zoneinfo.zip"}
	main()
}

This approach allows you to test the CLI behavior directly by injecting arguments into os.Args before calling main() within the test function.