How to test code using JSON in Golang?

WBOY
Release: 2024-06-02 13:05:56
Original
1143 people have browsed it

Testing code that uses JSON in Go is crucial, and this article provides the following steps: Write JSON data, encoding to byte slices using json.Marshal. Decode JSON data, parsing from byte slice to struct using json.Unmarshal.

如何在 Golang 中测试使用 JSON 的代码?

How to test code that uses JSON in Golang

Testing code that uses JSON in Golang is important to ensure the robustness of the application Sex is crucial. This article will guide you through the following steps for testing:

1. Write JSON data

import (
    "encoding/json"
    "fmt"
    "testing"
)

type Person struct {
    Name string `json:"name"`
    Age  int    `json:"age"`
}

func TestEncodeJSON(t *testing.T) {
    person := Person{Name: "John", Age: 30}

    b, err := json.Marshal(person)
    if err != nil {
        t.Errorf("Error encoding JSON: %v", err)
    }

    expected := `{"name":"John","age":30}`
    if string(b) != expected {
        t.Errorf("Expected '%s', got '%s'", expected, string(b))
    }
}
Copy after login

2. Decode JSON data

func TestDecodeJSON(t *testing.T) {
    jsonStr := `{"name":"Mary","age":25}`

    person := Person{}
    err := json.Unmarshal([]byte(jsonStr), &person)
    if err != nil {
        t.Errorf("Error decoding JSON: %v", err)
    }

    expected := Person{Name: "Mary", Age: 25}
    if person != expected {
        t.Errorf("Expected '%v', got '%v'", expected, person)
    }
}
Copy after login

Practical case

Consider a function that reads a JSON configuration file:

func LoadConfig(path string) (Config, error) {
    b, err := ioutil.ReadFile(path)
    if err != nil {
        return Config{}, err
    }

    config := Config{}
    err = json.Unmarshal(b, &config)
    if err != nil {
        return Config{}, err
    }

    return config, nil
}
Copy after login

The following test case will verify whether the LoadConfig function reads correctly JSON file:

func TestLoadConfig(t *testing.T) {
    // 创建一个包含 JSON 数据的临时文件
    f, err := ioutil.TempFile("", "config")
    if err != nil {
        t.Errorf("Error creating temporary file: %v", err)
    }
    defer os.Remove(f.Name())

    _, err = f.WriteString(`{"key":"value"}`)
    if err != nil {
        t.Errorf("Error writing to temporary file: %v", err)
    }
    if err := f.Close(); err != nil {
        t.Errorf("Error closing temporary file: %v", err)
    }

    config, err := LoadConfig(f.Name())
    if err != nil {
        t.Errorf("Error loading config: %v", err)
    }

    expected := Config{Key: "value"}
    if config != expected {
        t.Errorf("Expected '%v', got '%v'", expected, config)
    }
}
Copy after login

The above is the detailed content of How to test code using JSON in Golang?. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!