dsds33222 2019-09-16 03:58
浏览 133
已采纳

如何编写干净的集成测试

I want to write an integration test using Go and MySQL. But I confused how to do this clean. I have 4 functions: create, get, update, and delete. Is it a good practice if I just have one test function to test all my code? For example:

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
    })
}

If I have code like above, I just have one test function to test all my code. If I want to add a test case, I just add to TestCRUD() function. Is it a good practice?

Or should I write test function for each CRUD function? So I have 4 test functions and every test function also have many test cases. How can I write my integration test clean?

  • 写回答

1条回答 默认 最新

  • douyi4991 2019-09-16 04:23
    关注

    If you think in maintainability and clean code, IMHO I would recommend you to test each CRUD functions in a different test.

    Regarding your question about multiple test cases I would say that a good approach is to use DDT (data-driven-testing or table-driven-testing). Something like:

    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)
                }
            })
        }
    }
    

    Using gotests you can generate clean and nice tests for your functions.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分
  • ¥15 Macbookpro 连接热点正常上网,连接不了Wi-Fi。
  • ¥15 delphi webbrowser组件网页下拉菜单自动选择问题
  • ¥15 linux驱动,linux应用,多线程
  • ¥20 我要一个分身加定位两个功能的安卓app
  • ¥15 基于FOC驱动器,如何实现卡丁车下坡无阻力的遛坡的效果
  • ¥15 IAR程序莫名变量多重定义
  • ¥15 (标签-UDP|关键词-client)
  • ¥15 关于库卡officelite无法与虚拟机通讯的问题