如何在Golang测试文件中构造导入

如何在Golang测试文件中构造导入

问题描述:

I have functions defined in main.go that aren't accessible in main_test.go. However, in some online tutorials, I see that functions are accessible: I would like to understand the difference, as well as how to structure these in a go-idiomatic way .

Specifically, I have an application with multiple binaries:

myapp/cmd/app/main.go
myapp/cmd/cli/main.go

I currently have a lot of simple unit test logic I run in the func main of the main.go files. I'm just testing individual functions and having them print their output, I'm not trying to invoke the whole power of the "testing" suite, if I can avoid it.

Since my tests in the top of my main.go are so long at this point, I would like to move them to specific test files, in for example:

myapp/cmd/app/main_test.go
myapp/cmd/cli/main_test.go

This works well enough with my makefile:

# Makefile

all: test build
build:
    go build -o cmd/app/main cmd/app/main.go
    go build -o cmd/cli/main cmd/cli/main.go
test:
    go test ./cmd/app/main_test.go
    go test ./cmd/cli/main_test.go

If I just want to run my testfiles, I'd like to take the item in my app/main.go

// cmd/app/main.go
package main

func definedInMain(m string) string {
  // 
}

func main() {
  m := definedInMain("1")
  fmt.Println(m)
  // all the rest of my app's logic...
}

And run it in my main_test.go

// cmd/app/main_test.go

package main

// no imports, I hope?

func testDefinedInMain() {
  m := definedInMain("1")
  fmt.Println(m)  
}

However, this fails with:

undefined: definedInMain
FAIL

I am confused that I have to import all these functions into my main_test.go files (and even when I try, it suggests "can't load package: ... myapp/cmd/app/main" in any of: ...")

Is there a clean and go-idiomatic way for me to test my very simple unit tests in test files and run my functions in main files without a lot of rewriting imports or other substantial re-architecting?

From some links, I had the impression if I made a main_test.go, the imports would follow on their own (as they seem to in these examples).

So, you can see I am a bit confused tutorials get their functions imported for free, and I do not, and I just want to understand the magic better.

Is it just the case my function, definedInMain, is private because it's lowercased? I do actually want this function to be private, but I'd expect it to be exported to the main_test.go file the same way it is usable in main.go. Do I have to make it fully public to have tests in another file? That doesn't seem correct, eg, "it is only possible to unit test public methods in go?"

If @Mustafa Simav wants to post that answer, I'll accept, but if not, to close this out:

The solution was to use non-local imports with the full path below $GOPATH. The whatever_test.go does get automagic imports correctly, even of non-exported, lowercase functions, which is exactly what I wanted to unit test. This was just hard to see owing to the imports.