Test exported and internal behavior
Test exported and internal behavior
A test may use the same package name as production code, allowing access to unexported declarations. A test in package calc_test is a separate external test package; import calc by its module path and use its exported API. Choose black-box tests for public contracts and internal tests for details that are worth checking directly.
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
--- calc.go ---package calc
func normalize(n int) int { if n < 0 { return 0 } return n}func Count(n int) int { return normalize(n) }
--- calc_test.go ---package calc
import "testing"
func TestNormalize(t *testing.T) { if normalize(-1) != 0 { t.Fatal("negative must become zero") }}The test has package calc, so it can call normalize. This may be useful for complex internal rules, but tests tightly coupled to private implementation can make refactoring unnecessarily difficult.
Expected result (timings and formatting may vary; essential text shown):
--- PASS: TestNormalizeTest only the public contract
--- go.mod ---module example.test/lesson
go 1.23
--- calc.go ---package calc
func normalize(n int) int { if n < 0 { return 0 } return n}func Count(n int) int { return normalize(n) }
--- public_test.go ---package calc_test
import ( calc "example.test/lesson" "testing")
func TestCount(t *testing.T) { if calc.Count(-1) != 0 || calc.Count(4) != 4 { t.Fatal("bad count") }}The external test imports the module root, whose package name is calc. It cannot name calc.normalize. The public behavior can remain unchanged even if normalize is removed or renamed. Both test styles may coexist in one directory.
Expected result (timings and formatting may vary; essential text shown):
--- PASS: TestCountTry it locally
Implement exported Twice and verify it from package calc_test using the module import path. Test 0 and 5. 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
Testing fundamentals 05: Test exported and internal behavior
Check the lesson objective before moving on.
Which test can call an unexported function directly?
Why use an external test package?