在 Golang 中使用不同的值多次运行单元测试

and*_*dms 5 testing unit-testing go

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

应用程序.go

package main

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

func add(a int, b int) int {
    return a + b
}
Run Code Online (Sandbox Code Playgroud)

但想做类似的事情:

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)
    }
}
Run Code Online (Sandbox Code Playgroud)

Eli*_*sky 17

在 Go 中,这是通过表驱动测试来完成的。我建议您阅读上一句中链接的整个页面,但这里有一个简单的示例来演示它(来自 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)
            }
        })
    }
}
Run Code Online (Sandbox Code Playgroud)