6

I'm trying to test a function multiple times with different values using the testing module in Golang - does anyone know how to do this? I know how to do it with one value.

app.go

package main

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

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

but want to do something like:

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

1 Answer 1

20

In Go this is done with table-driven tests. I suggest you read the whole page linked in the previous sentence, but here's a simple example demonstrating it (from 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)
            }
        })
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.