I have a question about generating code coverage in Go(lang) projects.I have this simple structure:
ROOT/
config/
handlers/
lib/
models/
router/
main.go
config
contains configuration in JSON and one simple config.go
that reads and parses JSON file and fills the Config
struct which is used then when initializing DB connection. handlers
contains controllers (i.e. handlers of respective METHOD+URL described in router/routes.go
). lib
contains some DB, request responder and logger logic. models
contains structs and their funcs to be mapped from-to JSON and DB. Finally router
contains the router and routes definition.
Basically just by testing one single handler I ensure that my config, logger, db, responder, router and corresponding model are invoked (and tested somehow as well).
Now if this would be a PHP or Java or I don't know what else language, having and running that single handler test would create a code coverage also for all other invoked parts of code even if they are in different folders (i.e. packages here). Unfortunately, this is not the case in Go.
And there is very little code in most of my lib
files having just one method (like InitDB()
or ReadConfig()
or NewRouter()
or Logger()
) so to be able to have code coverage for them I have to create stupid tests in these packages as well while they were already invoked and tested by testing the main URLs handling packages.
Is there any way how to get code coverage from packages also for included other packages within one project?
You can import your packages within a single test and write tests for them based on how they'll be used within your application. For example, you can have one test, main_test.go
which imports all the other packages, and then you write tests for the methods in the imported packages.
Like this (in main_test.go):
package main
import (
"testing"
"lib"
"models"
"handlers"
// etc
)
// testing code here
However, in my personal opinion, it might be better to make sure that each package does what it should and that only. The best way to do that, is by testing the individual package itself, with its own test suite.