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

Solution 1:

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

Solution 2:

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.