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()
// 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()
}
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).
- https://medium.com/@thejasbabu/testing-in-golang-c378b351002d (where the Reverse function is not explicitly imported in reverse_test.go)
- https://tutorialedge.net/golang/intro-testing-in-go/ (where the Calculate function is not explicitly imported in main_test.go)
- https://blog.alexellis.io/golang-writing-unit-tests/
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.
Aucun commentaire:
Enregistrer un commentaire