官术网_书友最值得收藏!

addInt_test.go

You might have also noticed in TestSimpleVariadicToSlice that we duplicated a lot of logic, while the only varying factor was the input and expected values. One style of testing, known as Table-driven development, defines a table of all the required data to run a test, iterates over the "rows" of the table and runs tests against them.

Let's look at the tests we will be testing against no arguments and variadic arguments:

// addInt_test.go 
 
package main 
 
import ( 
    "testing" 
) 
 
func TestAddInt(t *testing.T) { 
    testCases := []struct { 
        Name     string 
        Values   []int 
        Expected int 
    }{ 
        {"addInt() -> 0", []int{}, 0}, 
        {"addInt([]int{10, 20, 100}) -> 130", []int{10, 20, 100}, 130}, 
    } 
 
    for _, tc := range testCases { 
        t.Run(tc.Name, func(t *testing.T) { 
            sum := addInt(tc.Values...) 
            if sum != tc.Expected { 
                t.Errorf("%d != %d", sum, tc.Expected) 
            } else { 
                t.Logf("%d == %d", sum, tc.Expected) 
            } 
        }) 
    } 
} 
主站蜘蛛池模板: 揭东县| 襄城县| 桦南县| 盘山县| 株洲县| 五原县| 西贡区| 曲水县| 福海县| 大同市| 凤庆县| 广汉市| 通州区| 祁阳县| 云阳县| 余姚市| 普兰店市| 昭通市| 广水市| 瑞昌市| 胶南市| 南川市| 观塘区| 黄浦区| 蕲春县| 宿州市| 巴塘县| 肃南| 浦城县| 新兴县| 镇平县| 双牌县| 巍山| 邵阳市| 济南市| 闽清县| 武乡县| 瓦房店市| 昭觉县| 林西县| 怀宁县|