it's not a Go thing per-se, it depends on your preference, but:
a. don't test main
. main should only invoke tested code, preferably in other packages. Provide as much code coverage as you can to those packages, and leave main as trivial as possibly. That's a good practice regardless of coverage. So that's not really a problem.
b. Don't use log.Fatal
for testable code, just return errors. You can keep log.Fatal
in application init code, i.e. - in main
:). So if main calls readConfig
and it fails, it just returns an error (very testable!). The added application behavior of log.Fatal
is main's job - the configuration reader shouldn't handle things like deciding if we should quit the application, right? It just reads configurations and tells you if it succeeded. The application decides what to do with it.
So your code might look like:
func readConfig(path string) (Config, error) {
var cfg Config
file, err := ioutil.ReadFile(path)
if err != nil {
return cfg, err
}
err = json.Unmarshal(file, &cfg)
if err != nil {
return cfg, err
}
return cfg, nil
}
func main() {
config, err := readConfig("config.json")
if err != nil {
log.Fatal(err)
}
}
And now you've separated logic from application behavior, and readConfig
is perfectly testable.
manpreet
Best Answer
2 years ago
I'm pretty new to go testing coming from a background of PHP with PHPUnit tests.
In PHP it's pretty much reliously preached that you need 100% coverage. In Go most stuff i've read about tests seem to minimal, without stuff like provoking errors.
For example my small program:
now in my example I would have issues with coverage because main() isn't covered at all in Unit tests (How should it?)
And the 2 log.Fatal()'s are not covered at all.
My question is how do I write my tests exactly in go? Do I do it in a less strict style not testing every possible scenario or can I do annotation like in php with
@expectedException \InvalidArgumentException
Can I or should I test the main function? If not can I ignore it from the coverage tool somehow? Should I consider a testing framework? Most testing tutorial are nice but very short and only introducing simple tests.