【问题标题】:Running unit tests multiple times with different values in Golang在 Golang 中使用不同的值多次运行单元测试
【发布时间】:2021-07-25 12:28:51
【问题描述】:

我正在尝试使用 Golang 中的测试模块多次测试具有不同值的函数 - 有人知道该怎么做吗?我知道如何用一个值来做到这一点。

app.go

package main

func main () {
    value := add(1, 2)
}

func add(a int, b int) int {
    return a + b
}

但想做类似的事情:

app_test.go

package main
import (
    "testing"
)

TestAdd1(t *test.T) {
    res := add(1, 2)
    if(res != 3) {
        t.Error("Got: %d, want: %d", res, 3)
    }
}


TestAdd2(t *test.T) {
    res := add(2, 2)
    if(res != 4) {
        t.Error("Got: %d, want: %d", res, 4)
    }
}

【问题讨论】:

    标签: unit-testing go testing


    【解决方案1】:

    在 Go 中,这是通过 table-driven tests 完成的。我建议您阅读上一句中链接的整个页面,但这里有一个简单的示例来演示它(来自 gobyexample.com):

    // We'll be testing this simple implementation of an
    // integer minimum. Typically, the code we're testing
    // would be in a source file named something like
    // `intutils.go`, and the test file for it would then
    // be named `intutils_test.go`.
    func IntMin(a, b int) int {
        if a < b {
            return a
        }
        return b
    }
    
    // A test is created by writing a function with a name
    // beginning with `Test`.
    func TestIntMinBasic(t *testing.T) {
        ans := IntMin(2, -2)
        if ans != -2 {
            // `t.Error*` will report test failures but continue
            // executing the test. `t.Fatal*` will report test
            // failures and stop the test immediately.
            t.Errorf("IntMin(2, -2) = %d; want -2", ans)
        }
    }
    
    // Writing tests can be repetitive, so it's idiomatic to
    // use a *table-driven style*, where test inputs and
    // expected outputs are listed in a table and a single loop
    // walks over them and performs the test logic.
    func TestIntMinTableDriven(t *testing.T) {
        var tests = []struct {
            a, b int
            want int
        }{
            {0, 1, 0},
            {1, 0, 0},
            {2, -2, -2},
            {0, -1, -1},
            {-1, 0, -1},
        }
    
        for _, tt := range tests {
            // t.Run enables running "subtests", one for each
            // table entry. These are shown separately
            // when executing `go test -v`.
            testname := fmt.Sprintf("%d,%d", tt.a, tt.b)
            t.Run(testname, func(t *testing.T) {
                ans := IntMin(tt.a, tt.b)
                if ans != tt.want {
                    t.Errorf("got %d, want %d", ans, tt.want)
                }
            })
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2017-03-09
      • 1970-01-01
      • 1970-01-01
      • 2012-03-26
      • 2019-12-10
      • 1970-01-01
      • 2014-10-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多