Home > Backend Development > Golang > How to Reuse Test Code from Imported Packages in Go with Unexported Functions?

How to Reuse Test Code from Imported Packages in Go with Unexported Functions?

Patricia Arquette
Release: 2024-11-04 03:48:29
Original
883 people have browsed it

How to Reuse Test Code from Imported Packages in Go with Unexported Functions?

Reusing Test Code in Imported Packages in Go

In your directory structure, you have a test utility function in pkg1_test.go that you wish to use in main_test.go, which imports pkg1. However, the function in pkg1_test.go uses an unexported function in pkg1, making it unavailable outside of the package.

Consider the following approaches:

Moving the Function to pkg1.go

While moving the function to pkg1.go would make it accessible in main_test.go, it could lead to the function being included in the binary generated by go build. This is undesirable for test-only functions.

Creating a Separate Test Utility Package

Moving the function to a separate test utility package and importing it manually in *_test.go files seems ideal. However, the function still requires access to internal methods in pkg1, which may not be exported.

A Hybrid Approach

For your specific scenario, a hybrid approach offers a solution:

  1. Move the test utility function from pkg1_test.go to a new package, let's call it testutils.
  2. Import testutils in both main_test.go and pkg1_test.go.
  3. In pkg1_test.go, add a function like this:

    <code class="go">func getPrivateData() []byte {
        // Code to get internal data from pkg1
    }</code>
    Copy after login
  4. In testutils, load the private data from getPrivateData in pkg1_test.go and use it to perform the necessary tests.

This approach allows you to reuse your test utility function while keeping it separate from the production code and avoiding the problem of unexported functions.

The above is the detailed content of How to Reuse Test Code from Imported Packages in Go with Unexported Functions?. 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