问题描述
这是我的目录层次结构:
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
我仅在pkg1_test.go
中具有一些用于测试的实用程序功能. main.go
导入pkg1
.现在,我想在我的main_test.go
中使用这些功能.搜索之后,我发现了两种可能的解决方案,但是它们都有一些缺点:
I have some utility functions for tests only in pkg1_test.go
. main.go
imports pkg1
. Now I want to use these functions in my main_test.go
. After searching I found two possible solutions, but both of them have some drawbacks:
- 将这些功能移至
pkg1.go
.但是,这些功能可能包含在go build
生成的二进制文件中. - 将这些功能移动到单独的
testutility
程序包中,然后将其手动导入到*_test.go
中.问题在于这些函数在pkg1
中使用了一些内部方法.
- Move these functions into
pkg1.go
. However these functions might be contained in binaries generated bygo build
. - Move these functions into a separate
testutility
package, then import it in*_test.go
manually. The problem is that these functions use some internal methods inpkg1
.
所以我想知道是否有更好的解决方案来解决这个问题.
So I was wondering whether there is a better solution to this problem.
推荐答案
如果您在整个项目的*_test.go
文件中使用此功能,则最好将其移动到utils包中并将该包导入到*_test.go
中.此外,由于此util软件包仅用于测试目的,因此建议将pkg1
内部函数的输出保存在支持文件中,并在调用支持软件包的函数(应使用pkg1
的私有函数)时加载该输出.
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
. 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
.
这篇关于如何重用导入包中的测试代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!