Go Unit Testing: how to specify path to tests or package under test

I am creating some unit tests for my code, for the first time in Go.

I have successfully had tests running where all files are dumped in the same directory (eg main.go package having a function being tested by main_test.go). By running the command go test, the tests and associated code are successfully executed.

It seems however more prudent to me to keep the test packages/files separate from my actual project files, so I moved the main_test.go file into a sub-directory titled Unit_tests. I am now baffled as to how you get the tests to run again.

I have tried (in CLI) to run: go test /home/user/go_directory/project/main.go

however this simply results in an error stating I cannot use an absolute path. I wouldn’t think I should have to have the test in $PATH, as this may then be confused with other tests/packages.

What is the generally accepted practice with regard to where and how to store unit test files? Where should I be storing them? how do I execute them when not stored in the same directory as my project?

I am also not sure, when executing the command go test xyz.go whether xyz specifies the unit test itself, or the package under test. nobody clarifies this online.

I am using: VS Code 1.47.3 Ubuntu 18.04 (all up to date) Go Version go1.15.2 linux/amd64

In general I’d be the same opinion, but in go it is indeed idiomatic to have the _test.go within the same folder as the SUT.

If main.go and main_test.go both are in package main then that won’t work. main is not importable.

As said above: colocated to the SUT.

The idiom is, to test functions and methods for $name.go in a testfile $name_test.go for better discoverability.

In that case, your unittests had to import the package you want to test as any other package would need to import them.

According to go help test, go test does not accept file names, but package names only. Though following the idiomatic colocation of tests, you have to specify the package under test, and it will search for colocated *_test.go files and run tests from them.

If you really want to have dislocated tests, you should still be able to run them using go test ./... or by specifying the package that contains the tests, and go should figure out what else needs compilation because of the imports.

Thank you, that clarified a few things. Yes, since posting I found another answer to a very similar question on Stack Overflow, and it seems to be standard practice to put the test files in the same folder as the project/package under test. Thanks again for confirming this. I will follow Go best practice and just do the same.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.