Moving tests to a sub folder and importing package main


I built an application in the root folder with *.go package set to main.

I also build some test *_test.go in the same ‘root’ directory.

So anyway I moved ALL my *_test.go files to a sub folder ‘test’. I changed the package names to ‘test’ but the test code cannot access the code in the root (main) dir.

Is there a way of importing …/. as in a relative ‘up one level’ because I cannot make it work.

I spent hours making a go.mod. Do I require a go.mod file and all that implies, ‘go mod tidy’ ‘requires’ with package names etc.

What is the best/simplest way to isolate the tests from the code.

I have to say that I find the modules structure very confusing.

Please help


A test for a package lives in the same folder as the package it tests. This is how it works in go.


Hi @stuartdd,

In additon to @NobbZ’s advice, note that package main cannot be imported by other packages.

If you want to keep the root dir clear from _test.go files, consider factoring out all code that has tests from the main package to a library package.

Your main package will then contain only some startup code and glue code that would not be suitable for unit testing anyway.


Ok. Thanks. I will not worry about it then.

I wanted to do it properly and now I know what properly is :blush:



Thanks for the advice but I have noticed the any declarations in the test file become visible in all files.

For example a test method calling a ‘test’ utility method in order to save replication in the test code.

I made the mistake of creating a close(t *testing.T, name string) method in the test file. This caused errors when I closed a channel using close(c). It was a little strange at the time as VSCode highlighted the error but compiled it anyway.

It took me some time to sort it because the code compiled but broke when it ran!

I have the measure of it now but I can see an opportunity for introducing errors into code. Is there a better way?


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