Home  >  Article  >  Backend Development  >  How to test code using JSON in Golang?

How to test code using JSON in Golang?

WBOY
WBOYOriginal
2024-06-02 13:05:561162browse

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))
    }
}

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)
    }
}

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
}

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)
    }
}

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!

Statement:
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