英文:
How do I test that specific methods are being called in the main() function
问题
我想测试main()
函数中是否调用了newrelic.NewConfig
和newrelic.NewApplication
。
import (
"github.com/newrelic/go-agent"
)
func main() {
/* NewRelic配置 */
newRelicConfig := newrelic.NewConfig("my-app-name",
os.Getenv("NEW_RELIC_LICENSE_KEY"))
app, err := newrelic.NewApplication(newRelicConfig)
// 其他代码
}
我应该将该代码移动到main
包中的一个单独函数中吗,像这样:
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
}
这样我就可以检查SetupNewRelicConfig
是否被调用了。
测试这个的正确方法是什么?
英文:
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?
答案1
得分: 2
你希望通过自动化测试还是作为某种类型的运行时断言来测试这个功能?
假设你想将自动化测试添加到你的测试套件中:
你需要找到一种方法来模拟NewRelic包导出的函数。
一种非常简单的方法在这里描述了("Monkey Patching in Golang"):
https://husobee.github.io/golang/testing/unit-test/2015/06/08/golang-unit-testing.html
一种更全面的方法是将这些函数调用添加到一个可以被你的测试套件替换的结构体中。可以参考依赖注入的方式,如下所述:
https://medium.com/@zach_4342/dependency-injection-in-golang-e587c69478a8
最后,可以考虑使用一个模拟框架。我在stretchr的testify项目中使用过模拟功能,效果非常好。
英文:
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.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论