在Go中测试未导出的功能

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?

If your files are truly in the same package, this should not be an issue. I am able to run the below test with no problem.

directory structure:

~/Source/src/scratch/JeffreyYong-Example$ tree .
.
├── example.go
└── example_test.go

example.go:

package example

import "fmt"

func unexportedFunc() {
    fmt.Println("this totally is a real function")
}

example_test.go

package example

import "testing"

func TestUnimportedFunc(t *testing.T) {
    //some test conditions
    unexportedFunc()
}

test command:

~/Source/src/scratch/JeffreyYong-Example$ go test -v .

output:

=== RUN   TestUnimportedFunc
this totally is a real function
--- PASS: TestUnimportedFunc (0.00s)
PASS
ok      scratch/JeffreyYong-Example     0.001s

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

Running go test /path/to/testfile_test.go Will not automatically compile any defenitions made in /path/to/testfile.go

You can run the test with go test /path/to/ instead.