HiveBrain v1.2.0
Get Started
← Back to all entries
snippetgoMajor

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

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
privateunexportedhowfunctiongolangtest

Problem

I was interested in creating unit test for "unexported (private) functions" in go. However, its basically really hard to create unit tests form them in the test package because I have to make them "public". Which in the end, defeats the whole point of them being private. The point is that these helper function help modularize and now that they are modular, it would be nice to be able to create unit tests for them without making them available to everyone except the testing package, nice they are not functions that should be accessed or used by anyone else except the testing suite or the actual package itself.

Any suggestions? Is it possible to only export to its own package and 1 additional package or something of that sort in go?

Solution

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

Code Snippets

package mypkg

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

type private struct {
  privateField string
}

Context

Stack Overflow Q#24622388, score: 87

Revisions (0)

No revisions yet.