[英]Golang: How to reuse test code in imported package?
Here is my directory hierarchy: 这是我的目录层次结构:
/
|-- main.go // package main, an HTTP server which accepts request and calls C/U APIs in pkg1 to finish certain task
|-- main_test.go // wants to call veryfyTaskNumber in pkg1_test
|-- pkg1 // package pkg1, CRUD APIs with Retrieve&Delete unexported for safety
|-- pkg1_test.go // contains a function verifyTaskNumber(*testing.T, taskName string, expectedNo int) which calls internal Retrieve function in pkg1
I have some utility functions for tests only in pkg1_test.go
. 我只在
pkg1_test.go
有一些实用函数用于测试。 main.go
imports pkg1
. main.go
进口pkg1
。 Now I want to use these functions in my main_test.go
. 现在我想在
main_test.go
使用这些函数。 After searching I found two possible solutions, but both of them have some drawbacks: 搜索后我发现了两种可能的解决方案,但它们都有一些缺点:
pkg1.go
. pkg1.go
However these functions might be contained in binaries generated by go build
. go build
生成的二进制文件中。 testutility
package, then import it in *_test.go
manually. testutility
包中,然后手动将其导入*_test.go
。 The problem is that these functions use some internal methods in pkg1
. pkg1
使用了一些内部方法。 So I was wondering whether there is a better solution to this problem. 所以我想知道是否有更好的解决方案来解决这个问题。
If you use this function in *_test.go
file throughout the project it's a good idea to move it to a utils package and import this package in your *_test.go
. 如果您在整个项目的
*_test.go
文件中使用此函数,最好将其移动到utils包并在*_test.go
导入此包。 Moreover since this util package is used only for testing purposes I suggest to save the output of the internal function of pkg1
in a support file and load it when you call the support package's function which should use the private function of pkg1
. 此外,由于此util包仅用于测试目的,我建议将
pkg1
的内部函数的输出保存在支持文件中,并在调用支持包的函数时加载它,该函数应使用pkg1
的私有函数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.