dsfsw1233 2017-02-18 01:33
浏览 9
已采纳

进行每个测试的测试设置和拆卸

I am using go "testing" package. Running my tests like below.

func TestMain(m *testing.M) {

   ...
   // Setup
   os.Exit(m.Run())
   // Teardown
}

This will run a setup before any test is run, and a teardown after all tests are complete. And I do need this, as the setup sets the DB up. But also, I need, and yet to find out a way to run a per-test setup/teardown. For the unit tests I am running, I would like to clear the DB before every test, so that there are no issues with the content of the DB causing unexpected behavior.

  • 写回答

2条回答 默认 最新

  • duanjiagu0655 2017-02-18 02:03
    关注

    As shown in the article "Go unit test setup and teardown" from Kare Nuorteva, you could use a setup function which returns... a teardown function to you defer.

    See this gist:

    func setupSubTest(t *testing.T) func(t *testing.T) {
        t.Log("setup sub test")
        return func(t *testing.T) {
            t.Log("teardown sub test")
        }
    }
    

    The setup function is in charge of defining and returning the teardown one.

    For each test, for instance in a table-driven test scenario:

    for _, tc := range cases {
        t.Run(tc.name, func(t *testing.T) {
            teardownSubTest := setupSubTest(t)
            defer teardownSubTest(t)
    
            result := Sum(tc.a, tc.b)
            if result != tc.expected {
                t.Fatalf("expected sum %v, but got %v", tc.expected, result)
            }
        })
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 finalshell节点的搭建代码和那个端口代码教程
  • ¥15 用hfss做微带贴片阵列天线的时候分析设置有问题
  • ¥50 我撰写的python爬虫爬不了 要爬的网址有反爬机制
  • ¥15 Centos / PETSc / PETGEM
  • ¥15 centos7.9 IPv6端口telnet和端口监控问题
  • ¥120 计算机网络的新校区组网设计
  • ¥20 完全没有学习过GAN,看了CSDN的一篇文章,里面有代码但是完全不知道如何操作
  • ¥15 使用ue5插件narrative时如何切换关卡也保存叙事任务记录
  • ¥20 海浪数据 南海地区海况数据,波浪数据
  • ¥20 软件测试决策法疑问求解答