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

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) 
            } 
        }) 
    } 
} 
主站蜘蛛池模板: 北碚区| 潍坊市| 彭州市| 固安县| 朝阳市| 那坡县| 石狮市| 乌鲁木齐县| 行唐县| 蛟河市| 湘潭县| 乌什县| 巫溪县| 扎赉特旗| 台东市| 崇礼县| 奉化市| 汉沽区| 全州县| 新源县| 潍坊市| 辽中县| 雷山县| 彭阳县| 金寨县| 通山县| 夹江县| 新宾| 正镶白旗| 光山县| 甘孜| 福建省| 攀枝花市| 怀柔区| 神池县| 阿拉善左旗| 井研县| 通许县| 聊城市| 平安县| 城步|