Choose internal and external package tests
Choose internal and external package tests
An internal test uses the same package name and can inspect unexported identifiers. An external test uses the package name plus _test and imports the public package. Prefer public behavior for contracts callers rely on; use internal tests for invariants that are otherwise hard to observe. Both use _test.go files and run with go test.
Create the files shown below in a fresh directory, then run go test -count=1 -v ./... there. The separator lines are file labels, not source code. Go 1.23 is used for these local examples.
--- go.mod ---module example.test/lesson
go 1.23
--- lesson.go ---package lesson
func clamp(n int) int { if n < 0 { return 0 } return n}func Quantity(n int) int { return clamp(n) }
--- lesson_test.go ---package lesson
import "testing"
func TestLesson(t *testing.T) { if got := clamp(-3); got != 0 { t.Fatal(got) }}Here clamp is private. The test can check the internal negative-input rule without exporting a helper just for tests. The cost is coupling: renaming or deleting clamp requires updating this test even if callers see no difference.
Expected result (timings and formatting may vary; essential text shown):
--- PASS: TestLessonProtect the exported contract
--- go.mod ---module example.test/lesson
go 1.23
--- lesson.go ---package lesson
func Quantity(n int) int { if n < 0 { return 0 } return n}
--- lesson_test.go ---package lesson_test
import ( "example.test/lesson" "testing")
func TestLesson(t *testing.T) { for _, c := range []struct{ in, want int }{{-3, 0}, {0, 0}, {4, 4}} { if got := lesson.Quantity(c.in); got != c.want { t.Fatalf("Quantity(%d)=%d", c.in, got) } }}The external test is unaffected by removing clamp. It imports the module path from go.mod, not a local filesystem path. A package can contain both styles (with distinct files and nonconflicting names). Avoid exporting internals merely to satisfy tests.
Expected result (timings and formatting may vary; essential text shown):
--- PASS: TestLessonTry it locally
Create an exported IsAvailable(stock int) bool function and use an external test for negative, zero and positive stock. Use a fresh module with the same go.mod shown above; run go test -count=1 -v ./...
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Advanced testing 01: Choose internal and external package tests
Check the lesson objective before moving on.
Which test can call an unexported helper directly?
Which test better survives replacement of a private helper?