dougou7782 2017-07-05 14:04
浏览 151
已采纳

TestMain无法运行

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.

  • 写回答

2条回答 默认 最新

  • dpbf62565 2017-07-05 18:56
    关注

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

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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 问题遇到的现象和发生背景 360导航页面千次ip是20元,但是我们是刷量的 超过100ip就不算量了,假量超过100就不算了 这是什么逻辑呢 有没有人能懂的 1000元红包感谢费
  • ¥30 计算机硬件实验报告寻代
  • ¥15 51单片机写代码,要求是图片上的要求,请大家积极参与,设计一个时钟,时间从12:00开始计时,液晶屏第一行显示time,第二行显示时间
  • ¥15 用C语言判断命题逻辑关系
  • ¥15 原子操作+O3编译,程序挂住
  • ¥15 使用STM32F103C6微控制器设计两个从0到F计数的一位数计数器(数字),同时,有一个控制按钮,可以选择哪个计数器工作:需要两个七段显示器和一个按钮。
  • ¥15 在yolo1到yolo11网络模型中,具体有哪些模型可以用作图像分类?
  • ¥15 AD9910输出波形向上偏移,波谷不为0V
  • ¥15 淘宝自动下单XPath自动点击插件无法点击特定<span>元素,如何解决?
  • ¥15 曙光1620-g30服务器安装硬盘后 看不到硬盘