2015-12-16 46 views
1

我割上Golang我的牙齒和挖掘到table driven tests後,我遇到了以下問題:Golang:多返回值函數表測試

我有一個返回多個值

// Halves an integer and and returns true if it was even or false if it was odd. 
func half(n int) (int, bool) { 
    h := n/2 
    e := n%2 == 0 
    return h, e 
} 
功能

我知道half(1)返回值應該是0, falsehalf(2)它應該匹配1, true,但我似乎無法弄清楚如何把它放在一張桌子上。

怎麼會有類似於以下的東西?

var halfTests = []struct { 
    in int 
    out string 
}{ 
    {1, <0, false>}, 
    {3, <1, true>}, 
} 

有沒有其他更習慣的方法呢?

僅供參考,以下是一些測試類似於一個FizzBu​​zz功能,採用表:提前

var fizzbuzzTests = []struct { 
    in int 
    out string 
}{ 
    {1, "1"}, 
    {3, "Fizz"}, 
    {5, "Buzz"}, 
    {75, "FizzBuzz"}, 
} 

func TestFizzBuzz(t *testing.T) { 
    for _, tt := range fizzbuzzTests { 
     s := FizzBuzz(tt.in) 
     if s != tt.out { 
      t.Errorf("Fizzbuzz(%d) => %s, want %s", tt.in, s, tt.out) 
     } 
    } 
} 

感謝,

編輯

大意如下的東西嗎?

var halfTests = []struct { 
    in int 
    half int 
    even bool 
}{ 
    {1, 0, false}, 
    {2, 1, true}, 
} 

func TestHalf(t *testing.T) { 
    for _, tt := range halfTests { 
    h, e := Half(tt.in) 
    if h != tt.half { 
     t.Errorf("Half(%d) => %d, want %d", tt.in, h, tt.half) 
    } 

    if e != tt.even { 
     t.Errorf("Half(%d) => %t, want %t", tt.in, e, tt.even) 
    } 
    } 
} 

回答

3

只需將另一個字段添加到包含第二個返回值的結構中。例如:

var halfTests = []struct { 
    in int 
    out1 int 
    out2 bool 
}{ 
    {1, 0, false}, 
    {3, 1, true}, 
} 

您的測試函數看起來像下面這樣:

func TestHalf(t *testing.T) { 
    for _, tt := range halfTests { 
     s, t := half(tt.in) 
     if s != tt.out1 || t != tt.out2 { 
      t.Errorf("half(%d) => %d, %v, want %d, %v", tt.in, s, t, tt.out1, tt.out2) 
     } 
    } 
} 
+0

編輯適當格式化的建議的問題。 – Gaston

+0

太棒了,感謝您的評論:D – Gaston