[英]Exporting Golang packages for testing?
In trying to come with test against code that uses the following struct: 在尝试对使用以下结构的代码进行测试时:
type DatabaseSt struct {
DBName string
DBConnectionStr string
dbConnection *sql.DB
InterpolateParams bool
//Archived Databases
MinFinancialYear int
MaxFinancialYear int
}
//DatabaseContext The context to use if the use of a database is needed.
type DatabaseContext struct {
*Context
Database DatabaseSt
}
I stumbled upon this Medium article claiming that you can export Golang packages, with their internals, in test code. 我偶然发现了这篇中型文章,声称您可以在测试代码中导出带有其内部结构的Golang软件包。 Unfortunately, I'm not sure what they mean in their last words:
不幸的是,我不确定它们的最终含义是什么:
export_test.go only be include when we run go test, so it not pollute your API, and user never access them(not like java's @VisibleForTesting), and it build a bridge let unexported one accessible in math_test
仅当我们运行go test时,export_test.go才被包括在内,因此它不会污染您的API,并且用户从不访问它们(不像Java的@VisibleForTesting),并且它搭建了一个桥,让未导出的桥可以在math_test中访问
and even worse, replication of it leads to nowhere fast: 更糟糕的是,它的复制无法快速实现:
/* Here, context
is the package containing the struct I want full access to */ / *在这里,
context
是包含我想完全访问* /的结构的包
I basically need to be able to set the dbConnection
of that DatabaseSt
for testing, without modifying the source code. 我基本上需要能够设置该
DatabaseSt
的dbConnection
进行测试,而无需修改源代码。
Add the following file named export_test.go: 添加以下名为export_test.go的文件:
package context
func SetDbConnection(DatabaseSt *ds, db *sql.DB) {
ds.dbConnection = db
}
Use it from other test files in the same directory like this: 从同一目录中的其他测试文件中使用它,如下所示:
package context_test
import "context"
func FooTest(t *testing.T) {
...
context.SetDbConnection(ds, db)
...
}
Alternatively, write the test in the context package so you have full access to the members: 或者,在上下文包中编写测试,以便您可以完全访问成员:
package context
func FooTest(t *testing.T) {
...
ds.dbConnection = db
...
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.