go - 有没有一种好方法来更新传递给 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
在传递函数的地方使用简单的东西,但我似乎无法在任何地方找到如何做到这一点。如果有人能指出我正确的方向,我将不胜感激。谢谢!
解决方案
如果只是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)
}
})
}
}
推荐阅读
- php - Laravel 获取渲染路径的视图名称
- javascript - 具有自定义身份验证的 Ionic 3 应用程序
- office365 - 如何在 Microsoft GraphAPI 中获取未经许可的用户
- javascript - 我正在尝试在我的 Ruby 应用程序中使用 AJAX 重新加载 div。div 带有“if 条件”
- c# - 将 PDF 嵌入 WPF WebBrowser,然后打印
- python - 导入对象的名称
- android-studio - 无法将我的三星 Note 3 Neo 连接到 Android Studio 3.1.3
- apache-flink - Flink Dashboard 上不同的数字和颜色代表什么?
- bash - 如何检查变量是否来自这种格式?#细绳 ”......”?
- webpack - 同一页面上的两个 aurelia 应用程序绑定两次