How to reuse test code in imported package? [duplicate]

谁都会走 提交于 2019-12-01 02:27:19

问题


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 by go 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 in pkg1.

So I was wondering whether there is a better solution to this problem.


回答1:


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.



来源:https://stackoverflow.com/questions/38712120/how-to-reuse-test-code-in-imported-package

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!