如何为嵌套JSON对应的struct结构体添加模拟测试哑数据
Go嵌套结构体模拟数据构造方案
你可以按照结构体的嵌套层级逐层完成初始化,以下是可直接运行的完整示例,生成的模拟数据结构和API反序列化得到的结构完全一致,可直接传入测试函数验证业务逻辑:
package main import ( "fmt" "time" ) // 你原有的结构体定义 type Info struct { Accounts []struct { AccountUID string `json:"accountUid"` AccountType string `json:"accountType"` DefaultCategory string `json:"defaultCategory"` Currency string `json:"currency"` CreatedAt time.Time `json:"createdAt"` Name string `json:"name"` } `json:"accounts"` } func main() { // 构造模拟测试数据 mockInfo := Info{ Accounts: []struct { AccountUID string `json:"accountUid"` AccountType string `json:"accountType"` DefaultCategory string `json:"defaultCategory"` Currency string `json:"currency"` CreatedAt time.Time `json:"createdAt"` Name string `json:"name"` }{ // 第一个测试账户 { AccountUID: "acc_20240501001", AccountType: "PRIMARY", DefaultCategory: "cat_001", Currency: "CNY", CreatedAt: time.Date(2024, 5, 1, 9, 30, 0, 0, time.UTC), Name: "个人日常账户", }, // 第二个测试账户 { AccountUID: "acc_20240612002", AccountType: "SAVINGS", DefaultCategory: "cat_002", Currency: "USD", CreatedAt: time.Date(2024, 6, 12, 15, 20, 0, 0, time.UTC), Name: "外币储蓄账户", }, }, } // 测试验证数据示例 fmt.Printf("共构造%d个测试账户:\n", len(mockInfo.Accounts)) for idx, acc := range mockInfo.Accounts { fmt.Printf("%d. 账户名:%s,类型:%s,货币:%s,创建时间:%s\n", idx+1, acc.Name, acc.AccountType, acc.Currency, acc.CreatedAt.Format(time.RFC3339)) } }
优化建议
如果测试场景需要频繁构造该结构的模拟数据,可以把内部的匿名结构体提取为独立的命名结构体,简化初始化代码:
// 提取内部账户结构为独立类型 type Account struct { AccountUID string `json:"accountUid"` AccountType string `json:"accountType"` DefaultCategory string `json:"defaultCategory"` Currency string `json:"currency"` CreatedAt time.Time `json:"createdAt"` Name string `json:"name"` } // 调整后的外层Info结构 type Info struct { Accounts []Account `json:"accounts"` } // 此时构造模拟数据的代码会更简洁 mockInfo := Info{ Accounts: []Account{ { AccountUID: "acc_003", AccountType: "INVESTMENT", // 其余字段按需赋值即可 }, }, }
如果需要生成大量随机测试数据,可以配合Go生态的测试造数工具快速生成字段值,无需手动逐个赋值。
内容的提问来源于stack exchange,提问作者danny.lyubenov
相关产品推荐
相关产品推荐

