如何重用导入包中的测试代码? [英] How to reuse test code in imported package?
问题描述
这是我的目录层次结构:
<预><代码>/|-- main.go//package main,一个接受请求并调用pkg1中的C/U API来完成某项任务的HTTP服务器|-- main_test.go//想调用pkg1_test中的veryfyTaskNumber|-- pkg1//打包 pkg1、带有 Retrieve&Delete 的 CRUD API 未导出以确保安全|-- pkg1_test.go//包含一个函数 verifyTaskNumber(*testing.T, taskName string, expectedNo int) 调用 pkg1 内部的 Retrieve 函数我只有在 pkg1_test.go
中有一些用于测试的实用函数.main.go
导入 pkg1
.现在我想在我的 main_test.go
中使用这些函数.搜索后我找到了两种可能的解决方案,但它们都有一些缺点:
- 将这些函数移到
pkg1.go
中.但是,这些函数可能包含在go build
生成的二进制文件中. - 将这些函数移动到单独的
testutility
包中,然后手动将其导入*_test.go
.问题是这些函数使用了pkg1
中的一些内部方法.
所以我想知道这个问题是否有更好的解决方案.
如果你在整个项目的 *_test.go
文件中使用这个函数,最好将它移到一个 utils 包中在你的 *_test.go
中导入这个包.此外,由于此 util 包仅用于测试目的,我建议将 pkg1
的内部函数的输出保存在支持文件中,并在调用应使用私有函数的支持包的函数时加载它pkg1
.
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
. 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:
- 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.
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
.
这篇关于如何重用导入包中的测试代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!