答案:文章介绍了在Go项目中如何使用testing包和encoding/json对结构体进行JSON序列化与反序列化测试。首先定义带有json tag的User结构体,然后编写TestUser_MarshalJSON测试正常序列化、TestUser_MarshalJSON_OmitEmpty验证omitempty行为、TestUser_UnmarshalJSON测试反序列化正确性,并可通过testify库简化字段比较,确保API数据交互的可靠性。

测试 JSON 序列化在 Go 项目中很常见,尤其是在构建 API 或处理数据传输时。你需要确保结构体能正确地编码为 JSON 字符串,也能从 JSON 正确解码回来。下面介绍如何用 Golang 的 testing 包和 encoding/json 来完成这类测试。
假设你有一个表示用户信息的结构体:
<pre class="brush:php;toolbar:false;">type User struct {
ID int `json:"id"`
Name string `json:"name"`
Email string `json:"email,omitempty"`
}
字段上的 json tag 控制了序列化后的键名,omitempty 表示当字段为空时不会出现在 JSON 输出中。
在 user_test.go 中写一个测试,检查结构体能否正确转成预期的 JSON。
立即学习“go语言免费学习笔记(深入)”;
<pre class="brush:php;toolbar:false;">func TestUser_MarshalJSON(t *testing.T) {
user := User{
ID: 1,
Name: "Alice",
Email: "alice@example.com",
}
data, err := json.Marshal(user)
if err != nil {
t.Fatalf("marshal failed: %v", err)
}
expected := `{"id":1,"name":"Alice","email":"alice@example.com"}`
if string(data) != expected {
t.Errorf("expected %s, got %s", expected, string(data))
}
}
这个测试验证了:
你可以再写一个测试,验证当 Email 为空时,它是否被省略。
Easily find JSON paths within JSON objects using our intuitive Json Path Finder
30
<pre class="brush:php;toolbar:false;">func TestUser_MarshalJSON_OmitEmpty(t *testing.T) {
user := User{
ID: 2,
Name: "Bob",
// Email 留空
}
data, err := json.Marshal(user)
if err != nil {
t.Fatalf("marshal failed: %v", err)
}
expected := `{"id":2,"name":"Bob"}`
if string(data) != expected {
t.Errorf("expected %s, got %s", expected, string(data))
}
}
除了序列化,你也应测试从 JSON 还原结构体是否正确。
<pre class="brush:php;toolbar:false;">func TestUser_UnmarshalJSON(t *testing.T) {
input := `{"id":3,"name":"Charlie","email":"charlie@example.com"}`
var user User
err := json.Unmarshal([]byte(input), &user)
if err != nil {
t.Fatalf("unmarshal failed: %v", err)
}
if user.ID != 3 {
t.Errorf("expected ID 3, got %d", user.ID)
}
if user.Name != "Charlie" {
t.Errorf("expected Name Charlie, got %s", user.Name)
}
if user.Email != "charlie@example.com" {
t.Errorf("expected Email charlie..., got %s", user.Email)
}
}
这种测试确保你的结构体能正确解析外部输入的 JSON 数据。
如果字段较多,手动比较每个字段会很繁琐。可以使用 reflect.DeepEqual 或第三方库如 testify/assert 简化断言。
<pre class="brush:php;toolbar:false;">import "github.com/stretchr/testify/assert"
func TestUser_UnmarshalJSON_WithTestify(t *testing.T) {
input := `{"id":4,"name":"Dana"}`
var user User
json.Unmarshal([]byte(input), &user)
expected := User{ID: 4, Name: "Dana"}
assert.Equal(t, expected, user)
}
这样代码更简洁,也更容易维护。
基本上就这些。只要覆盖典型场景:正常序列化、空字段处理、反序列化还原,就能保证你的结构体在 JSON 交互中表现可靠。
以上就是如何使用Golang测试JSON序列化的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号