The tests that you’ve written are in the same package as the production code. This allows you to test both exported and unexported functions.
If you want to test just the public API of your package, Go has a convention for specifying this. You still keep your test source code in the same directory as the production source code, but you use packagename_test for the package name. Let’s redo the initial test case, using an exported function instead. You can find the code in the examples/pubadder directory. In the adder_public.go file in pubadder package, the following exported function is declared:
func AddNumbers(x, y int) int {
return x + y
}
You test the function as public API by using the following code in a file in the pubadder directory named adder_public_test.go:
package pubadder_test
import (
"example.com/studynotes/pubadder"
"testing"
)
func TestAddNumbers(t *testing.T) {
result := pubadder.AddNumbers(2, 3)
if result != 5 {
t.Error("incorrect result: expected 5, got", result)
}
}
Notice that the package name for the test file is pubadder_test. You have to import example.com/studynotes/pubadder even though the files are in the same directory. To follow the convention for naming tests, the test function name matches the name of the AddNumbers function. Also note that you use pubadder.AddNumbers, since you are calling an exported function in a different package.
Just as you can call exported functions from within a package, you can test your public API from a test that is in the same package as your source code. The advantage of using the _test suffix in the package name is that it lets you treat your tested package as a “black box.” You are forced to interact with it only via its exported functions, methods, types, constants, and variables.
Tip
A package can include test source files that use the _test suffix for the package declaration alongside test source files that use the package name. This allows you to organize your tests for exported and unexported functions into different files.