首页 > 解决方案 > 有没有一种好方法来更新传递给 Golang 中子测试的结构

问题描述

我正在尝试编写一个表驱动测试来测试,例如,如果传递给函数的两个订单相同,

订单可以像

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
}

我想要做的是添加第二个测试,在其中更改 currOrder 上的 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,
        },
    }

在我看来,我不能[]struct在传递函数的地方使用简单的东西,但我似乎无法在任何地方找到如何做到这一点。如果有人能指出我正确的方向,我将不胜感激。谢谢!

标签: gotesting

解决方案


如果只是OrderId每个测试的不同,您可以只传递订单 id 并基于该内部循环构造 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)
            }
        })
    }
}

推荐阅读