Test CLI behavior and distribute binaries
Test CLI behavior and distribute binaries
CLI testing has two layers: directly call the command function with synthetic arguments and buffers, then run a built executable as a subprocess to verify actual exit status, stdin and output streams. Start with a table of expected cases.
package main
import ( "bytes" "fmt" "io" "strconv")
func divide(args []string, out, diag io.Writer) int { if len(args) != 2 { fmt.Fprintln(diag, "usage: divide A B") return 2 } a, e := strconv.Atoi(args[0]) b, f := strconv.Atoi(args[1]) if e != nil || f != nil { fmt.Fprintln(diag, "expected integers") return 2 } if b == 0 { fmt.Fprintln(diag, "zero divisor") return 1 } if _, err := fmt.Fprintln(out, a/b); err != nil { fmt.Fprintln(diag, "write failed") return 1 } return 0}func main() { for _, tc := range []struct { args []string want int }{{[]string{"6", "2"}, 0}, {[]string{"6", "0"}, 1}, {nil, 2}} { var out, diag bytes.Buffer got := divide(tc.args, &out, &diag) fmt.Println(got == tc.want, (out.Len() > 0) == (got == 0)) }}In actual testing.T tests, fail with useful case details rather than printing booleans. Build a fixture in a temporary directory, use exec.CommandContext with separate arguments, and assert ExitError.ExitCode on expected nonzero exits. Never execute arbitrary user-supplied command strings through a shell.
Expected output:
true truetrue truetrue trueIdentify the build target
package main
import ( "fmt" "runtime" "strings")
func main() { fmt.Println(runtime.GOOS != "", runtime.GOARCH != "") fmt.Println(strings.HasPrefix(runtime.Version(), "go"))}From the root of a module with a main package, run go build -o report . Build per OS and architecture, e.g. GOOS=linux GOARCH=amd64 go build -o report . in a POSIX shell. Windows uses different environment syntax and typically an .exe suffix. CGO_ENABLED=0 can simplify pure Go cross-builds but does not ensure every dependency works. Record source revision, Go version, target and SHA-256 checksum. Test on each target before release; cross-build success does not prove execution.
Expected output:
true truetrueTry it locally
Add an invalid operand case. Check status 2, empty stdout and nonempty diagnostic.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
CLI 07: Test CLI behavior and distribute binaries
Check the lesson objective before moving on.
What does a successful cross-build establish?
What should a subprocess test check for invalid usage?