如何编写干净的集成测试

How to write clean integration tests

我想使用 Go 和 MySQL 编写集成测试。但是我很困惑如何做到这一点。我有 4 个功能:创建、获取、更新和删除。如果我只有一个测试函数来测试我的所有代码,这是一种好习惯吗?例如:

func TestCRUD(t *testing.T){
    t.Run("success case", func(t *testing.T){
         // call create func

         // call update func

         // call get func

         // call delete func
    })
}

如果我有上面的代码,我只有一个测试函数来测试我所有的代码。如果我想添加一个测试用例,我只是添加到 TestCRUD() 函数。这是一个好习惯吗?

或者我应该为每个 CRUD 函数编写测试函数?所以我有 4 个测试函数,每个测试函数也有很多测试用例。我怎样才能干净地编写集成测试?

如果您考虑可维护性和整洁的代码,恕我直言,我建议您在不同的测试中测试每个 CRUD 函数。

关于您关于多个测试用例的问题,我会说一个好的方法是使用 DDT(数据驱动测试或 table 驱动测试)。类似于:

func Test_create(t *testing.T) {
    type args struct {
        // Define here your function arguments
        arg1 string,
        arg2 string,
    }
    tests := []struct {
        name string
        args args
        want bool // Your possible function output
    }{
    // TODO: Add test cases.
    }
    for _, tt := range tests {
        t.Run(tt.name, func(t *testing.T) {
            if got := create(tt.args.id); got != tt.want {
                t.Errorf("create() = %v, want %v", got, tt.want)
            }
        })
    }
}

使用 gotests 您可以为您的函数生成干净漂亮的测试。