In Go, testing functions should not be called from within the code itself. Instead, unit tests are meant to be executed using the go test
Go supports two types of unit testing: black-box and white-box.
Black-box testing tests exported functions from outside the package, simulating how external packages will interact with it.
White-box testing tests unexported functions from within the package itself.
Consider a package called example with an exported function Sum and an unexported utility function add.
<code class="go">// example.go package example func Sum(nums ...int) int { sum := 0 for _, num := range nums { sum = add(sum, num) } return sum } func add(a, b int) int { return a + b }</code>
Black-box testing (in example_test.go):
<code class="go">package example_test import ( "testing" "example" ) func TestSum(t *testing.T) { tests := []struct { nums []int sum int }{ {nums: []int{1, 2, 3}, sum: 6}, {nums: []int{2, 3, 4}, sum: 9}, } for _, test := range tests { s := example.Sum(test.nums...) if s != test.sum { t.FailNow() } } }</code>
White-box testing (in example_internal_test.go):
<code class="go">package example import "testing" func TestAdd(t *testing.T) { tests := []struct { a int b int sum int }{ {a: 1, b: 2, sum: 3}, {a: 3, b: 4, sum: 7}, } for _, test := range tests { s := add(test.a, test.b) if s != test.sum { t.FailNow() } } }</code>
In summary, unit tests should be executed using the go test command, and never called directly from within code. Black and white-box testing provide different levels of access to the package's implementation for testing purposes.
The above is the detailed content of How Can You Test Unexported Functions in Go?. For more information, please follow other related articles on the PHP Chinese website!