I am writing units test. I put all of the test files in other directory. Let's say the folder mypack.
There two files in the folder fun1_test.go and base.go.
The base.go has same common basic functions which are called by fun1_test.go. The base.go looks like:
package mypack_test
import (
.....
)
func Base1() {
// some code
}
The func1_test.go has functions which test func1. The func1_test.go looks like:
package mypack_test
import (
.....
)
func TestFunc1() {
// some code
Base1()
// some code
}
When I use command
go test func1_test.go base.go
There will be an error:
can't load package: package main: found packages mypack (func1_test.go) and mypack_test (base.go)
Can any one tell me why this happend. I know If the change the file base.go to base_test.go. The command will work ok. But I want to know why.
UPDATE:
I notice some of you guys misunderstanding the problem. The problem is not about if the two file need the other packages or one can call one.
The problem is that: If you have two file with same package, the package name looks like xxx_test
. But the two files' name are yyy_test.go and zzz.go. When using go test yyy_test.go zzz.go
command, there will be an error said they two file not in same packages.
The error are: can't load package: package main: found packages xxx (yyy_test.go) and xxx_test (zzz.go)
You should follow go's best practices.
That is:
Package names should contain only letters with no underscores.
Test file should be name of original file + test like: base.go
- base_test.go
.
Run test by going to packages directory and running go test
.
If you make those changes, your tests should run without any problems.
If you checkout the go help test
command there is this:
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.
What is happening is that your file yyy_test.go
is recognised as a test file because of its _test.go
ending. The package defined in that file package xxx_test
is considered to be the test version of the xxx
package.
See this stack answer for desc: https://stackoverflow.com/a/31443271/6376471
Then, along comes zzz.go
which is not recognised as a test file, because it's missing the _test.go
suffix, it has a packge xxx_test
which is not considered to be a test package.
This means that essentially you are defining the packages xxx_test
from zzz.go
and xxx
from yyy_test.go
, even though yyy_test.go
actually defines xxx_test
, but it's in a test file so handled differently.
Solutions:
zzz.go
as a test file by making it zzz_test.go
.zzz.go
to have the non test package name package xxx
instead of package xxx_test
.