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 单片机学习顺序问题!!
  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)
  • ¥15 相敏解调 matlab
  • ¥15 求lingo代码和思路
  • ¥15 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应
  • ¥15 matlab基于pde算法图像修复,为什么只能对示例图像有效
  • ¥100 连续两帧图像高速减法
  • ¥15 如何绘制动力学系统的相图