繁体   English   中英

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

[英]Is there a good way to update structs passed to sub-tests in Golang

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

订单可以像

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并使用我传入 function 的东西,但我似乎无法在任何地方找到如何做到这一点。 如果有人能指出我正确的方向,我将不胜感激。 谢谢!

如果每个测试中只有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)
            }
        })
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM