Unit tests - same vs separate package

2,182 views
Skip to first unread message

Stevo Slavić

unread,
Jan 30, 2018, 8:51:58 AM1/30/18
to golan...@googlegroups.com
Hello Go community,

Official docs recommend putting unit tests in same package as package under test, see:

Practical experience (see https://medium.com/@matryer/5-simple-tips-and-tricks-for-writing-unit-tests-in-golang-619653f90742#03db) suggests it's better to put tests to a dedicated package so it can test exported API only of the package under test, and if there's value to test the package internals too then put another test suite file to the same package with a special file name to make it clear it's meant to fiddle with internals.

Do these suggestions make sense? If so, would it make sense to make them official recommended practice? Maybe in Effective Go?

Kind regards,
Stevo Slavic.

Ian Lance Taylor

unread,
Jan 30, 2018, 9:59:25 AM1/30/18
to Stevo Slavić, golang-nuts
Go already supports both approaches. Internal tests of package p are
themselves in package p. External tests are in package p_test. In
both cases the tests can be in the same directory in xxx_test.go
files. This is documented at
https://golang.org/cmd/go/#hdr-Test_packages . Effective Go doesn't
seem to say anything about testing today. If we think we need to say
something, a blog article might be a better approach.

Ian

Sonia Keys

unread,
Jan 31, 2018, 9:18:34 AM1/31/18
to golang-nuts
Stevo, that's how I do it.  Most of my tests are in an _test package so I can be sure my exported API works.  Once in a while I want some extra tests on something not exported so those tests go in a separate source file.  And yes, I try to do something with the filename to indicate that it contains in-package tests.

Alex Buchanan

unread,
Jan 31, 2018, 10:05:21 PM1/31/18
to golang-nuts
FWIW, I did not know about this line:

"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."

In order to write integration/e2e tests while avoiding import cycles, most (not all) of our tests live in a dedicated "/tests" directory: https://github.com/ohsu-comp-bio/funnel/tree/master/tests 

Knowing about the line above, I think I'll encourage us to try to reorganize our tests back into the package structure and ditch the dedicated "/tests" directory. Might be too late for that though, for this project.

-A
Reply all
Reply to author
Forward
0 new messages