Sobes.tech
Senior

Do you know what table-driven testing is?

sobes.tech AI

Answer from AI

Table-driven testing is an approach to writing tests where a set of input data and expected results are described in the form of a table (usually a slice of structs), and then the test code iterates over this table, performing checks for each data set.

This makes it easy to add new cases, reduces code duplication, and improves readability.

Example in Go:

func TestSum(t *testing.T) {
    tests := []struct {
        name     string
        a, b     int
        expected int
    }{
        {"positive numbers", 2, 3, 5},
        {"zero", 0, 0, 0},
        {"negative numbers", -1, -2, -3},
    }

    for _, tt := range tests {
        t.Run(tt.name, func(t *testing.T) {
            result := Sum(tt.a, tt.b)
            if result != tt.expected {
                t.Errorf("Sum(%d, %d) = %d; want %d", tt.a, tt.b, result, tt.expected)
            }
        })
    }
}

Here, tests is a table of test cases, and the loop runs a test for each data set.