Testing: what's the difference between package x and x_test?

241 views
Skip to first unread message

Davi Marcondes Moreira

unread,
Oct 8, 2021, 2:34:21 PM10/8/21
to golang-nuts
Suppose a project has a package called abc, and this package has a few test files (*_test.go files).

I've noticed two different patterns when writing tests. Some files may declare its own package at the top of the file as below:

package abc

While others may declare its package as:

package abc_test

I've been trying to figure out what's the possible difference between these two naming conventions, but still, it's a mystery (at least for me). I've searched anything on the Go blog, but unfortunately, I could not find anything.

Does somebody here know the reason why some developers may write the package this way, and the difference between each form?

Best,

Sean Liao

unread,
Oct 8, 2021, 2:37:13 PM10/8/21
to golang-nuts
From https://pkg.go.dev/cmd/go#hdr-Test_packages

> Test files that declare a package with the suffix "_test" will be compiled as a separate package, and then linked and run with the main test binary.

Practically, this means no access to unexported things in the package

Ian Lance Taylor

unread,
Oct 8, 2021, 2:50:37 PM10/8/21
to Davi Marcondes Moreira, golang-nuts
Most people use "package abc". There are some exceptions.

1) In the standard library, any package that "testing" itself depends
upon can't use "package abc". For example, "testing" imports "bytes",
so "bytes" can't import "testing". That means that all the "bytes"
package tests have to be in package "bytes_test" instead. This
applies to several other standard library packages, but only matters
for the standard library itself.
2) Examples, as opposed to tests, are normally written as the same
kind of code that a user of the package would write. So examples are
normally in "abc_test" and import "abc" and write "abc.F()".
3) Some people want to explicitly write black box tests that don't
depend on any internal details of the package. Those people use
"abc_test" to ensure that they don't refer to unexported names.

Ian

Davi Marcondes Moreira

unread,
Oct 11, 2021, 3:06:31 PM10/11/21
to golang-nuts
Thanks for the responses, Sean and Ian!

I've been using the suffix "_test" to limit what can be tested (only the public methods) in order to think more about the design of the package itself, but I was always curious to know a little bit more about what's behind the difference between each choice, deeper than just this limitation to write tests.

Thanks again!
--
Reply all
Reply to author
Forward
0 new messages