Home > Backend Development > Golang > How to Reuse Test Code in Imported Packages While Keeping Internal Functions Private?

How to Reuse Test Code in Imported Packages While Keeping Internal Functions Private?

Mary-Kate Olsen
Release: 2024-11-04 02:39:01
Original
651 people have browsed it

How to Reuse Test Code in Imported Packages While Keeping Internal Functions Private?

Reusable Test Code in Imported Packages

In the provided scenario, you have a test file (main_test.go) that requires access to a test-only function in another package (pkg1_test.go). This poses the challenge of reusing test code across imported packages.

Possible Solutions and Their Drawbacks:

  • Move functions to pkg1.go: This makes the functions available to main_test.go but they may become part of the binary, which is undesirable.
  • Use a separate testutility package: While this allows you to group test-only functions, it introduces the dependency on internal methods in pkg1, creating potential problems.

Recommended Solution:

Instead of using either of the above methods, consider the following approach:

  1. Create a support package: Move the test-only functions to a new package, called support. This package should rely only on public interfaces of pkg1.
  2. Use a support file: In support, define a support file that contains the output of the private function from pkg1.
  3. Load support file in support function: In the support package, create a function that loads the support file and performs the necessary operations.
  4. **Call support function from main_test.go:** Import the support package in main_test.go and call the function that uses the private function from pkg1`.

This solution:

  • Keeps test-only code separate from production code.
  • Ensures that the internal function from pkg1 remains private.
  • Avoids issues with binary distribution.

The above is the detailed content of How to Reuse Test Code in Imported Packages While Keeping Internal Functions Private?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template