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

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) 
            } 
        }) 
    } 
} 
主站蜘蛛池模板: 德阳市| 林州市| 红河县| 三都| 南召县| 南京市| 新邵县| 汶上县| 邻水| 根河市| 罗城| 浪卡子县| 宿迁市| 双桥区| 申扎县| 葵青区| 屯昌县| 浪卡子县| 出国| 武乡县| 高平市| 黄陵县| 会宁县| 略阳县| 莲花县| 米易县| 全南县| 阿荣旗| 汉寿县| 南陵县| 崇文区| 翁牛特旗| 绥江县| 安陆市| 镇江市| 日喀则市| 南陵县| 佛山市| 论坛| 凤阳县| 临高县|