How to test a unexported (private) function in go (golang)?

create a test file within the package

library_test.go

package mypkg

func TestPrivateStruct(t *testing.T){
  pf := private{ "Private Field" }
  ....
}

library.go

package mypkg

type private struct {
  privateField string
}

go test mypkg -v will run your Tests with your private struct


if you want to use pkg_test name as a package name for test and still test unexported field a simple trick could be create export_test.go file in your package with package name pkg then export your unexported field in there for example

file code.go

package pkg 

func getFunc(){}

file export_test.go

package pkg 
var GetFunc = getFunc

file code_test.go

package pkg_test
func TestGetFunc(t *testing.T) {
    testFunc:=pkg.GetFunc

    //check your test scenario here

}

note that all these files are in the same folder

the solution is inspired from here


First, you can have both types of tests in the same location as your package by using the package name for internal tests (eg mypkg) and using the same package name with "_test" appended for "external" tests (eg mypkg_test). Both types of tests must be in files whose name ends in "_test.go".

BUT, the whole point of unit tests is to test the "external interface" (ie public functions) to your package. That is unit tests should always be "white box" tests (see White Box Testing). That way you can refactor your code and your tests won't break.

Of course, sometimes you want to check internal consistency, which is not possible through the "external interface". For that I have found assertions invaluable. Another possibility would be to add public "diagnostic" function(s) with names that indicate that they are not for normal use.