Home > Backend Development > Golang > How to Organize Go Tests and Examples in Subdirectories for a Cleaner Workspace?

How to Organize Go Tests and Examples in Subdirectories for a Cleaner Workspace?

Barbara Streisand
Release: 2024-11-17 21:07:01
Original
428 people have browsed it

How to Organize Go Tests and Examples in Subdirectories for a Cleaner Workspace?

Golang Sub-Directory Testing

Question: Is it possible to create a Go package with tests and examples organized in subdirectories to maintain a cleaner workspace?

Answer: Yes. You can run Go tests recursively using the go test ./... command, listing all the packages to test.

Test File Placement

Subdirectory Test Files:

If you place your _test.go files in a subfolder, the go test ./... command will include them. However, you must prefix exported variables and functions with the package name to enable access in the test file. Non-exported content remains inaccessible.

Same Directory Test Files:

Despite the option for subdirectory test files, keeping them alongside the main source file remains preferable due to easier accessibility.

Code Coverage

For code coverage using -cover or -coverprofile:

  • Use go test -coverpkg=./... ./... for coverage of all packages.
  • Alternatively, use go-cover-treemap.io for interactive coverage visualization.

Integration Testing Coverage

Starting with Go 1.20, coverage tooling extends to integration tests:

  • Use go build -cover -o myprogram.exe myprogram.go to create an executable with coverage.
  • Run GOCOVERDIR=somedata ./myprogram.exe to collect coverage data.
  • Coverage files will be generated in somedata.

Separate Package Testing

According to kbolino, you can place tests in a separate package without requiring a separate directory. This allows test files to be named foo_test and reside in the same directory as the package foo, while still restricting access to private members.

The above is the detailed content of How to Organize Go Tests and Examples in Subdirectories for a Cleaner Workspace?. 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