GO 中的测试列表

Testing lists in GO

我正在尝试在 GO 中实施测试。但是我正在努力处理结构中列表的语法。

package primeFactor

import "testing"

var testCases = []struct {
    p        int
    expected []int
}{
    {15, [3,5]},
    {26, [2,13]},
    {37, [37]},
    {42, [2,3,7]},
}

func TestPrimeFactor(t *testing.T) {
    for _, test := range testCases {
        observed := PrimeFactor(test.p)
        if observed != test.expected {
            t.Error("For p = %d, expected %t. Got %t.",
                test.p, test.expected, observed)
        }
    }
}

我的输出错误是:

expected ']', found ','
: expected operand, found '{'
: expected ';', found 'for'

感谢您的帮助。谢谢

你当初为什么要写那个?那不是 Go 语法。来自 the spec:

A slice literal describes the entire underlying array literal. Thus, the length and capacity of a slice literal are the maximum element index plus one. A slice literal has the form

[]T{x1, x2, … xn}

因此,在您的情况下:

var testCases = []struct {
    p        int
    expected []int
}{
    {15, []int{3, 5}},
    {26, []int{2, 13}},
    {37, []int{37}},
    {42, []int{2, 3, 7}},
}

该规范非常易读,并没有人们想象的那么可怕。您可能想要完整地了解一下,并将其放在附近以供参考。

Toni 的回答解决了您的具体问题,但要解决您要使用的比较切片的其他问题 reflect.DeepEqual

看看这个例子:

package main

import (
    "fmt"
    "reflect"
)

func main() {
    observed := []int{1, 2}
    expected := []int{1, 3}

    if reflect.DeepEqual(observed, expected) {
        fmt.Println("Slices are the same")
    } else {
        fmt.Println("Slices are different")
    }
}

https://play.golang.org/p/_JRQ5bqmJf

...为了完整起见,这里只是一个编写您自己的函数的简单示例,您的测试可以调用该函数来比较切片:

func slicesMatch(a, b []int) bool {
    la := len(a)
    lb := len(b)

    if la != lb {
        return false
    }

    for i := 0; i < la; i++ {
        if a[i] != b[i] {
            return false
        }
    }

    return true
}

View it on the Playground