How to reuse test code in imported package?
11,768
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
.
Comments
-
lz96 almost 2 years
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
importspkg1
. Now I want to use these functions in mymain_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.
- Move these functions into
-
cmp almost 8 yearsA package with the utilities for testing is the best way here.
-
Subhas about 5 yearsA package with test utility will help everyone else except the package where those relevant testing sources actually exist, due to cycling import issue. i.e. "pkg1" has a bunch of structs that you want to test, and a "util" package has some testing utilities which depend on this package. This "util" can be used everywhere else except "pkg1" due to cyclic import.
-
Bestbug about 5 yearsMaybe I wasn't clear when I wrote the first answer but I really don't see the point to create a utils package for testing without a proper isolation for pkg1. We should have a little bit more of comprehation about how the pkg1 was developed and how the test function call the pkg1 function before discussing about the possible cycling import. If you have a similar problem and you want an opinion feel free to ask :)