0

I have a package and many test files within.

web
 |- client.go
 |- client_test.go
 |- server.go
 |- server_test.go
 |- ...

If I want to run go test client_test.go, it report an error for me.

package web  // not the package name web_test

func TestHost(t *testing.T) {
      hostPort, hostNoPort := hostPortNoPort()
}

// error: undefined hostPortNoPort
// But this function actually defined in the client.go
ccd
  • 5,788
  • 10
  • 46
  • 96

2 Answers2

2

This will not work. The reason is when you run go test, go performs a build to create a test executable and runs it to get results. The source of restriction is go build

From go help build

If the arguments to build are a list of .go files from a single directory, build treats them as a list of source files specifying a single package.

When you give only client_test.go as input to go test, go build will assume that this one file is a full package. So, it will not parse the file where hostPortNoPort has been defined. This triggers build error.

You only have two options.

  1. Place it in web_test package and run go test client_test.go
  2. Use go test -run to match the testing function names

Option 2 can be a pain unless there is some naming logic used for test function names.

Peter
  • 29,454
  • 5
  • 48
  • 60
praveent
  • 562
  • 3
  • 10
0

try this

go test -v client_test.go

maybe it can help you

  • It will fail if he is using any internal structs or, methods of package web. The reason being that go will try to build this file only. Without explicit import of web, other files in web package are not pulled in. If he uses, web_test then he will have to add explicit import for web package and your advice would work. – praveent Apr 22 '20 at 04:17