learn-go-with-tests
learn-go-with-tests copied to clipboard
Help people navigate around gomodules, package 'main', and writing tests
(context: applies to chapters with executable main
functions, e.g. 'dependency injection' and 'mocking')
There isn't a ton of information in the book yet around naming your modules. People probably figure out that if they want to have an easy way to run their code with e.g. go run
, they need the module to be called main
– which in turn causes issues when executing your tests with go test
. This pretty much sums it up nicely and links the corresponding go issues going a bit deeper: https://appliedgo.net/testmain/
Can we add something helping people navigate around this? I'm wondering what the canonical advice here should be?
- keep doing
go mod init main
, such that you can execute your code withgo run
, but execute your tests withgo test *.go
instead ofgo test .
? - do
go mod init <someothername>
, run your code by ~~building and executing it differently~~go run <someothername>
, keep testing withgo test .
- something else?
PS: I'm not sure how the popular IDEs/tools might implement their 'run test' and 'run program' functionality and if that should influence the above decision. VScode, for example, uses go test main
, which runs into issues with the first option above.
Edit: I realized pretty late that go run
takes the module name and everything runs nicely, sorry for all the noise. Still, this might be helpful pointing out more explicitly?