duanjiati1755 2017-06-14 18:44
浏览 48

找到TestMain多个定义

If I define, two tests, each with its own TestMain method, go test errors: "multiple definitions found of TestMain".

I can understand and was expecting this behaviour actually, because, there should not be more than one TestMain in the same package. However, I don't know what to do now. Each test suite has its own needs. I need to create distinct TestMains to setup the tests, of course, without renaming my packages.

I could do that easily in other languages with setup methods like before, after, which is unique to a test class.

I'll probably go and use testify's suites. Sad that this is not supported in stdlib.

Do you have any suggestions?

  • 写回答

1条回答 默认 最新

  • dsajkdadsa14222 2017-06-14 18:57
    关注

    You can use M.Run.

    func TestMain(m *testing.M) {
        setup()
        code := m.Run() 
        close()
        os.Exit(code)
    }
    

    See subtest for additional info.

    More detailed example:

    package main
    
    import (
        "testing"
    )
    
    func setup()    {}
    func teardown() {}
    
    func setup2()    {}
    func teardown2() {}
    
    func TestMain(m *testing.M) {
        var wrappers = []struct {
            Setup    func()
            Teardown func()
        }{
            {
                Setup:    setup,
                Teardown: teardown,
            },
            {
                Setup:    setup2,
                Teardown: teardown2,
            },
        }
    
        for _, w := range wrappers {
            w.Setup()
            code := m.Run()
            w.Teardown()
    
            if code != 0 {
                panic("code insn't null")
            }
        }
    }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向
  • ¥15 如何用python向钉钉机器人发送可以放大的图片?