In $GOPATH/src/my_app/foobar
I can't run go test
because foobar_test.go
requires access to constants declared in the main
package (to initialize databases etc). I have tried importing main
in foobar_test.go
, but it says it can't find main in vendor
, GOROOT
or GOPATH
. I also can't use foobar
package constants declared in other files, for the same reason.
I don't want to mock the database. How do I do this?
评论:
jerf:
xrpfanboy:My main packages typically end up very small [1], because I pull all of this out of them. There are some packages that are almost literally
func main() { app := myapp.Application() app.Run() }
Anything that you find yourself needing somewhere else, pull it out of the "main" package.
A common pattern is to have the repo organized as
maindir/ cmd/ application/ main.go
so that the command is separated, and it doesn't feel too strange that main.go may actually be fairly small. Having the top level of the repo be a main package is not exactly an "anti-pattern", but it's suitable only for projects that will not grow beyond a certain size where the whole thing fits in one package comfortably.
[1]: This small stuff ends up pretty messy, because I put all the plumbing together of the components in my main function. But even though it's a nasty few screenfuls of code, it's still pretty small, even in relatively large applications.
You can't import main package. Make sure your test uses package main as well and not something like main_test. You should be able to access variables inside the same package.
