Maxim Yefremov
Maxim Yefremov

Reputation: 14185

is it possible to place test files in subfolder

When I have module and its test in the same directory it works ok.

- module1.go
- module1_test.go

But when number of files and test files grows it is hard to navigate through code.

Is it possible to place go tests to subfolder for cleaner code structure? When I try to do it I got namespace error.

I placed file module1_test.go to folder ./test

- module1.go
- test/module1_test.go

Now I got error on testing:

test/module1_test.go:8: undefined: someFunc

My module1.go code:

package package1

func someFunc() {

}

My module1_test.go code:

package package1

import (
    "testing"
)

func TestsomeFunc(t *testing.T) {
    someFunc()
}

Upvotes: 2

Views: 418

Answers (1)

user4122236
user4122236

Reputation:

You can put the tests in another directory, but it is not common practice. Your tests will need to import the subject package and will not have access unexported methods in the subject package. This will work:

File $GOPATH/src/somepath/package1/module1.go

package package1

func SomeFunc() {

}

File $GOPATH/src/somepath/package1/test/module1_test.go

package test

import (
    "testing"
    "somepath/package1"
)

func TestSomeFunc(t *testing.T) {
    package1.SomeFunc()
}

A couple of notes:

  • I changed SomeFunc to an exported method so that the test can access it.
  • The test imports the subject package "somepath/package1"

Upvotes: 4

Related Questions