在Go中测试未导出的功能

Jef*_*ong 3 unit-testing go private-methods

我有一个名为的文件example.go,另一个名为的测试文件example_test.go,它们都在同一个程序包中。我想测试一些未导出的功能example.go

运行测试时,未导出的函数在中未定义example_test.go。我想知道在同一程序包中的测试文件中测试未导出函数的最佳约定是什么?

Geo*_*mas 8

这也适用于私有类型的私有成员函数。

例如。

abc.go 如下

package main

type abc struct {
        A string
}

func (a *abc) privateFunc() {

}
Run Code Online (Sandbox Code Playgroud)

abc_test.go 如下

package main

import "testing"

func TestAbc(t *testing.T) {
        a := new(abc)
        a.privateFunc()
}
Run Code Online (Sandbox Code Playgroud)

对此运行 go test 应该会让你完全通过,没有任何错误。

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


Opn*_*cus 5

如果您的文件确实位于同一软件包中,那么这应该不是问题。我能够毫无问题地运行以下测试。

目录结构:

~/Source/src/scratch/JeffreyYong-Example$ tree .
.
??? example.go
??? example_test.go
Run Code Online (Sandbox Code Playgroud)

example.go:

package example

import "fmt"

func unexportedFunc() {
    fmt.Println("this totally is a real function")
}
Run Code Online (Sandbox Code Playgroud)

example_test.go

package example

import "testing"

func TestUnimportedFunc(t *testing.T) {
    //some test conditions
    unexportedFunc()
}
Run Code Online (Sandbox Code Playgroud)

测试命令:

〜/ Source / src / scratch / JeffreyYong-Example $ go test -v。

输出:

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