Calling Test Functions from Non-Test Files
In Go, testing relies on specific conventions and methodologies. One of these conventions is that tests should be separated into their own test files, which must end with the "_test.go" suffix.
Can Test Functions be Called from Non-Test Files?
Short answer: No.
Contrary to your question, test functions cannot be directly invoked from non-test Go files. This separation ensures that testing remains distinct and independent from the code under test.
Testing Patterns in Go
Go primarily employs two types of unit testing:
Example
Consider the following "example" package with an exported "Sum" function and an unexported "add" function:
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 }
Black-box testing (example_test.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() } } }
White-box testing (example_internal_test.go):
package example_test 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() } } }
In conclusion, calling test functions from non-test files violates the principles of Go testing. Separate test packages should be used for unit testing purposes, adhering to the established workflow and conventions.
The above is the detailed content of Can You Call Go Test Functions From Non-Test Files?. For more information, please follow other related articles on the PHP Chinese website!