I want to test whether newrelic.NewConfig
and newrelic.NewApplication
are being called in the main()
function.
import (
"github.com/newrelic/go-agent"
)
func main() {
/* NewRelic configuration */
newRelicConfig := newrelic.NewConfig("my-app-name",
os.Getenv("NEW_RELIC_LICENSE_KEY"))
app, err := newrelic.NewApplication(newRelicConfig)
// followed by other code
}
Should I move that code into a separate function within the main
package, like:
func SetupNewRelicConfig() Application {
newRelicConfig := newrelic.NewConfig("my-app-name",
os.Getenv("NEW_RELIC_LICENSE_KEY"))
app, err := newrelic.NewApplication(newRelicConfig)
if err != nil {
log.Fatal(err)
}
return app
}
This way I can just check if the SetupNewRelicConfig
is called or not.
What is the right way to test this?
Are you hoping to test this from an automated test, or as a runtime assertion of some type?
Assuming you're looking to add an automated test to your suite:
You need to find a way to mock the functions exported by the NewRelic package.
A very cheap way to do this is described here ("Monkey Patching in Golang"):
https://husobee.github.io/golang/testing/unit-test/2015/06/08/golang-unit-testing.html
A more comprehensive approach requires you to add these function calls to a struct that can be swapped by your test suite. See dependency injection, as described here:
https://medium.com/@zach_4342/dependency-injection-in-golang-e587c69478a8
Finally, look into using a mocking framework. I've had great luck with the mocking in stretchr's testify project.