有没有一种好方法可以更新传递给Golang子测试的结构

有没有一种好方法可以更新传递给Golang子测试的结构,go,testing,Go,Testing,我试图编写一个表驱动测试来测试,比如说,如果传入函数的两个命令相同 什么地方有秩序 type Order struct { OrderId string OrderType string } 现在,我的测试看起来像: func TestCheckIfSameOrder(t *testing.T) { currOrder := Order{ OrderId: "1", OrderType: "SALE" } oldOrd

我试图编写一个表驱动测试来测试,比如说,如果传入函数的两个命令相同

什么地方有秩序

type Order struct {
    OrderId string
    OrderType string
}
现在,我的测试看起来像:

func TestCheckIfSameOrder(t *testing.T) {
    currOrder := Order{
         OrderId: "1",
         OrderType: "SALE"
    }
    oldOrder := Order{
         OrderId: "1",
         OrderType: "SALE"
    }
    tests := []struct {
        name string
        curr Order
        old  Order
        want bool
    }{
        {
            name: "Same",
            curr: currOrder,
            old:  oldOrder,
            want: true,
        },
    }
    for _, tt := range tests {
        t.Run(tt.name, func(t *testing.T) {
            got := checkIfSameOrder(tt.curr, tt.old)
            if got != tt.want {
                t.Errorf("want %v: got %v", tt.want, got)
            }
        })
    }

}

func checkIfSameOrder(currOrder Order, oldOrder Order) bool {
    if currOrder.OrderId != oldOrder.OrderId {
        return false
    }
    if currOrder.OrderType != oldOrder.OrderType {
        return false
    }
    return true
}
我想做的是添加第二个测试,在这里我更改curroder上的OrderId或其他内容,这样我的测试切片看起来像

tests := []struct {
        name string
        curr Order
        old  Order
        want bool
    }{
        {
            name: "Same",
            curr: currOrder,
            old:  oldOrder,
            want: true,
        },
        {
            name: "Different OrderId",
            curr: currOrder, <-- where this is the original currOrder with changed OrderId
            old:  oldOrder,
            want: false,
        },
    }
测试:=[]结构{
名称字符串
本票
旧秩序
想要布勒吗
}{
{
名称:“相同”,
curr:curroder,
旧秩序,
想要:真的,
},
{
名称:“不同的订单ID”,

curr:curroorder,如果每个测试中只有
OrderId
不同,您可以通过OrderId并基于该内部循环构造oldOrder和currOrder。
共享在整个过程中发生变化的全局变量一直会造成混乱。最好为每个测试初始化新变量

func TestCheckIfSameOrder(t *testing.T) {

    tests := []struct {
        name string
        currId string
        oldId  string
        want bool
    }{
        {
            name: "Same",
            currId: "1",
            oldId:  "1",
            want: true,
        },
        {
            name: "Different",
            currId: "1",
            oldId:  "2",
            want: true,
        },
    }
    for _, tt := range tests {
        t.Run(tt.name, func(t *testing.T) {
            curr := Order{
                OrderId: tt.currId,
                OrderType: "SALE"
            }
            old := Order{
                OrderId: tt.oldId,
                OrderType: "SALE"
            }

            got := checkIfSameOrder(curr, old)
            if got != tt.want {
                t.Errorf("want %v: got %v", tt.want, got)
            }
        })
    }
}

这只是结构的一部分,你可以随心所欲地填充它——你不确定这是怎么回事?