Golang Trick: Export unexport method for test

Exported and not exported

In Go, Exported identifiers start with an upper-case letter, and lower-case identifiers only could see in own package. We should only export real needed identifiers to outer, and let our api easy to use and maintain.

Golang Test

As practice, Go Test just write new file aside test target and with _test suffix. E.g. we want test sum.go, we should create a test file and sum_test.go and write test in it. just see https://golang.org/pkg/testing/

In xx_test, we have two choices for its package. One, use same package as target one(e.g. test math and use math). Or, use package with _test for test(e.g. test math with math_test).

In most cases, we should use later one with _test, test code just as a black box with some small windows. So we can’t access unexported identifiers. But how we access them in some special test case when we need it???

Export_test.go

Let us review what we need:

  • No exported unexport identifiers in product code
  • Exported some of them in test code

Solution is very simple..

For example we want to test sum function in sum.go with package math

And create a test file named sum_test.go in sum_test package

but…In math there only sum not Sum, so the trick in here is that we should create another test file(in here export_test.go) but in math package

export_test.go only be include when we run go test, so it not pollute your API, and user never access them(not like java’s @VisibleForTesting), and it build a bridge let unexported one accessible in math_test

It’s a simple trick but maybe useful ~ ~