Testing Unexported Functions in Go

gogofan picture gogofan · Sep 27, 2017 · Viewed 8.7k times · Source

I have a file called example.go and another test file called example_test.go and they are both in the same package. I would like to test some unexported functions in example.go

When I run the test, the unexported functions are undefined in example_test.go. I am wondering what is the best convention of testing unexported functions in a test file that are in the same package?

Answer

George Thomas picture George Thomas · Sep 18, 2018

This will also work for private member functions of a private type.

For example.

abc.go is as follows

package main

type abc struct {
        A string
}

func (a *abc) privateFunc() {

}

abc_test.go is as follows

package main

import "testing"

func TestAbc(t *testing.T) {
        a := new(abc)
        a.privateFunc()
}

Running go test on this should give you a full pass without any errors.

linux-/bin/bash@~/trials/go$ go test -v
=== RUN   TestAbc
--- PASS: TestAbc (0.00s)
PASS
ok      _/home/george/trials/go        0.005s