Testing Reusable Code in Imported Packages
When working with multiple packages and test files, it's common to encounter the need to reuse utility functions from one test to another. Consider the following directory hierarchy:
/<br>|-- main.go // package main, an HTTP server which accepts request and calls C/U APIs in pkg1 to finish certain task<br>|-- main_test.go // wants to call veryfyTaskNumber in pkg1_test<br>|-- pkg1 // package pkg1, CRUD APIs with Retrieve&Delete unexported for safety</p> <div class="code" style="position:relative; padding:0px; margin:0px;"><pre class="brush:php;toolbar:false">|-- pkg1_test.go // contains a function verifyTaskNumber(*testing.T, taskName string, expectedNo int) which calls internal Retrieve function in pkg1
In this scenario, main_test.go needs to access verifyTaskNumber() from pkg1_test.go, posing the following challenge: How can test code in imported packages be reused effectively?
Two common approaches are:
A more effective solution is to save the output of the internal function in the imported package to a support file. This file can then be loaded when the corresponding function in the utility package is called.
For example, if pkg1 has an unexported function Retrieve(), you can create a function in the utility package that loads the support file and calls Retrieve(). By using this approach, the utility package's functions can access internal methods from the imported package without compromising modularity or build artifacts.
The above is the detailed content of How to Reuse Test Code in Imported Packages Effectively?. For more information, please follow other related articles on the PHP Chinese website!