Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where to put shared code for tests in a Go package? [duplicate]

I have a Go package with multiple files. As of Go standard I am creating an associated test file for each source file in the package.

In my case the different tests use the same test helping functions. I don't want these functions to be in the package source files because it is only used for testing purpose. I also would like avoiding replicating this code in each test file.

Where should I put this code shared between all the test source files and not part of the package ?

like image 831
chmike Avatar asked Dec 03 '16 15:12

chmike


1 Answers

You just put it in any of the test files and that's all. Test files using the same package clause belong to the same test package and can refer to each other's exported and unexported identifiers without any import statements.

Also note that you're not required to create a separate _test.go file for each of the .go files; and you can have an xx_test.go file without having a "matching" xx.go file in the package.

For example if you're writing package a, having the following files:

a/
    a.go
    b.go
    a_test.go
    b_test.go

For black-box testing you'd use the package a_test package clause in a_test.go and b_test.go. Having a func util() in file a_test.go, you can use it in b_test.go too.

If you're writing white-box testing, you'd use package a in the test files, and again, you can refer any identifiers declared in a_test.go from b_test.go (and vice versa) without any imports.

Note that however if the package clauses in a_test.go and b_test.go do not match (e.g. a_test.go uses package a and b_test.go uses package a_test), then they will belong to different test packages and then you can't use identifiers declared in one another.

like image 99
icza Avatar answered Oct 19 '22 01:10

icza