我正在尝试使用黄金文件实现测试,但是,我的函数生成的 JSON 顺序有所不同,但保持相同的值。我已经实现了这里使用的比较方法:
但这取决于顺序。正如布拉德在这里所说:
JSON 对象是无序的,就像 Go 映射一样。如果您依赖于特定实现序列化 JSON 对象的顺序,则会遇到错误。
我编写了一些示例代码来模拟我的困境:
package main
import (
"bufio"
"encoding/json"
"fmt"
"io/ioutil"
"math/rand"
"os"
"reflect"
"time"
)
type example struct {
Name string
Earnings float64
}
func main() {
slice := GetSlice()
gfile, err := ioutil.ReadFile("testdata/example.golden")
if err != nil {
fmt.Println(err)
fmt.Println("Failed reading golden file")
}
testJSON, err := json.Marshal(slice)
if err != nil {
fmt.Println(err)
fmt.Println("Error marshalling slice")
}
equal, err := JSONBytesEqual(gfile, testJSON)
if err != …Run Code Online (Sandbox Code Playgroud)