简体   繁体   English

Golang:如何在导入的包中重用测试代码?

[英]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: 搜索后我发现了两种可能的解决方案,但它们都有一些缺点:

  • Move these functions into pkg1.go . 将这些功能移动到pkg1.go However these functions might be contained in binaries generated by go build . 但是,这些函数可能包含在go build生成的二进制文件中。
  • Move these functions into a separate 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM