TestMain没有运行

huangapple go评论115阅读模式
英文:

TestMain not run

问题

我有一个在Go中的测试包,测试一些依赖于读取配置的内容。我想在运行所有测试之前只读取一次配置,所以我尝试使用TestMain(m *testing.M)

main.go:

package tests

import (
	...
)

var logger = logging.MustGetLogger("tests")

func TestMain(m *testing.M) {
	logger.Info("Initializing test suite")

	viper.SetConfigName("config")
	viper.AddConfigPath("..\\..\\")
	err := viper.ReadInConfig()
	if err == nil {
		os.Exit(m.Run())
	} else {
		logger.Fatal("Could not read configuration")
	}
}

而且我在同一个目录(和包)中有另一个文件进行测试。

repository_test.go:

package tests

import (
	...
)

func TestCreation(t *testing.T) {
	aa := myModule.CreateRepository()
	assert.NotNil(t, aa)
}

我的问题是,测试失败,因为配置没有从文件中读取。当我尝试在Gogland中调试测试时,TestMain内部的断点不会被触发。当我从命令行运行测试时,我看不到任何来自TestMain的输出。

我应该做些特殊的事情来使它工作吗?根据我在网上的阅读,我了解到如果我定义了TestMain(m *testing.M),那么它将只运行一次,用于编写任何设置或拆卸代码的地方。

英文:

I have a test package in go which tests some stuff that depend on reading a configuration. I want to read that configuration once before running all tests so I'm trying to use TestMain(m *testing.M):

main.go:

package tests

import (
	...
)

var logger = logging.MustGetLogger("tests")

func TestMain(m *testing.M) {
	logger.Info("Initializing test suite")

	viper.SetConfigName("config")
	viper.AddConfigPath("..\\..\\")
	err := viper.ReadInConfig()
	if err == nil {
		os.Exit(m.Run())
	} else {
		logger.Fatal("Could not read configuration")
	}
}

And I have another file in the same directory (and package) with a test.

repository_test.go:

package tests

import (
	...
)

func TestCreation(t *testing.T) {
	aa := myModule.CreateRepository()
	assert.NotNil(t, aa)
}

My problem is that the test fails because the configuration is not read from the file. When I try to debug the test in Gogland a breakpoint inside TestMain is not hit. When I run the tests from command line I don't see any printouts from TestMain.

Is there something special I should do to make it work? From what I read online I understood that if I define TestMain(m *testing.M) then it's going to run just once for the package and that's where I'm supposed to write any setup or teardown code.

答案1

得分: 9

TestMain 只会在测试文件(后缀为 _test.go)中执行。

将该函数移动到 repository_test.go 文件中以修复此问题。

英文:

TestMain is only executed in test files (suffix _test.go).

Move the function to the repository_test.go file to fix this.

答案2

得分: 0

请确保运行配置设置为“包”而不是“文件”,在“运行 | 编辑配置... | Go Test | 您的配置名称”中进行设置,这样应该可以正常工作。如果不行,请发布IDE运行执行测试的命令。

英文:

Make sure that the run configuration is set to Package not File in Run | Edit Configurations... | Go Test | Name of your configuration and this should work. If it doesn't, please post the commands the IDE runs to execute the tests.

huangapple
  • 本文由 发表于 2017年7月5日 22:04:11
  • 转载请务必保留本文链接:https://go.coder-hub.com/44928478.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定