我如何才允许一个包只在测试时才能访问另一个包的未导出数据? [英] How can I allow one package access to another package's unexported data only when testing?

查看:100
本文介绍了我如何才允许一个包只在测试时才能访问另一个包的未导出数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

The Go Programming Language 中,第11.2.4节中,有一个外部测试通过访问 fmt.isSpace()的例子在 fmt export_test.go 中声明 IsSpace 文件。这似乎是一个完美的解决方案,所以我就这样做了:

 包a 

var x int

func Set(v int){
x = v
}

a / a_test.go

 包a 
导入测试

func TestSet(t * testing.T){
Set(42)
if x!= 42 {
t.Errorf(x ==%d(expected 42),x)



func Get()int {
return x
}
$ b

(在 a / 中运行 go test >可以正常工作。 )



b / b.go

<$ p







$ s $($) }

b / b_test.go

 包b 
导入(
测试
路径/至/ a


func TestCallSet(t * testing.T){
CallSet()
if r:= a.Get(); r!= 105 {
t.Errorf(Get()==%d(expected 105),r)
}
}

不幸的是,当我在 b / go test c $ c>,我得到:

  ./ b_test.go:11:undefined:a.Get 

试着用同时运行两组测试。 / code>没有帮助。



经过一段时间,我发现 * _test.go文件只有在运行该软件包的测试时才被编译到软件包中 (重点是我的)。 (换句话说,我可以通过 a_test 外部测试包在 a.Get > a / ,但不是来自 a / 以外的任何包。)

有没有其他一些方法可以允许一个包中的测试访问来自另一个包的其他包内的数据,以进行集成测试?

解决方案

< blockquote>

有没有其他一些方法可以允许一个包中的测试访问来自另一个包的其他包的内部数据,以进行集成测试?

没有。没有。


In The Go Programming Language, section 11.2.4, there is an example of of an external test accessing fmt.isSpace() via a declaration of IsSpace in fmt's export_test.go file. That seemed like the perfect solution, so that's what I did:

a/a.go:

package a

var x int

func Set(v int) {
    x = v
}

a/a_test.go:

package a
import "testing"

func TestSet(t *testing.T) {
    Set(42)
    if x != 42 {
        t.Errorf("x == %d (expected 42)", x)
    }
}

func Get() int {
    return x
}

(Running go test in a/ works fine.)

b/b.go:

package b
import "path/to/a"

func CallSet() {
    a.Set(105)
}

b/b_test.go

package b
import (
    "testing"
    "path/to/a"
)

func TestCallSet(t *testing.T) {
    CallSet()
    if r := a.Get(); r != 105 {
        t.Errorf("Get() == %d (expected 105)", r)
    }
}

Unfortunately, when I run go test in b/, I get:

./b_test.go:11: undefined: a.Get

Trying to run both sets of test at the same time with go test ./... did not help.

After some considerable poking around I discover that "The *_test.go files are compiled into the package only when running go test for that package" (emphasis mine). (So, in other words I could access a.Get from an a_test external test package in a/, but not from any package outside of a/.)

Is there some other way I can allow tests from one package to access otherwise-internal data from another package, for integration testing purposes?

解决方案

Is there some other way I can allow tests from one package to access otherwise-internal data from another package, for integration testing purposes?

No. There isn't.

这篇关于我如何才允许一个包只在测试时才能访问另一个包的未导出数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆