创建一个功能来测试从接口进行的编组/解组

时间:2018-12-10 16:12:52

标签: go reflection

我想创建一个简单的函数来测试编组/解组记录是否按预期工作。我只是在此示例中使用JSON:

package test

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

    "github.com/stretchr/testify/require"
)

func CheckRoundTripJSON(t *testing.T, record interface{}) {
    data, err := json.Marshal(record)
    require.NoError(t, err)
    fmt.Println("Record: ", record, " was encoded to: ", data, " - Type: ", reflect.TypeOf(record))

    result := reflect.Zero(reflect.TypeOf(record))
    inter := result.Interface()
    fmt.Println("Result: ", reflect.TypeOf(result), ", Inter: ", reflect.TypeOf(inter))

    {
        err = json.Unmarshal(data, &result)
        require.NoError(t, err)
        fmt.Println(data, " was deserialized to ", result, "type: ", reflect.TypeOf(result))
        require.Equal(t, record, result)
    }
    {
        err = json.Unmarshal(data, &inter)
        require.NoError(t, err)
        fmt.Println(data, " was deserialized to ", inter, "type: ", reflect.TypeOf(inter))
        require.Equal(t, record, inter)
    }
}


type Person struct {
    FirstName  string
    LastName   string
    Age        uint8
}

func TestPersonMarshalling(t *testing.T) {
    CheckRoundTripJSON(t, Person{
        FirstName: "Leonard",
        LastName:  "Nimoy",
        Age:       84,
    })
}

两个代码块都将出错。第一个离开result默认初始化,第二个离开inter指向包含反序列化数据的映射。

我想知道是否有办法在Golang中提供此界面和功能。根据文档,我最初尝试使用result.Addr(),但是Zero的结果无法寻址。

1 个答案:

答案 0 :(得分:1)

使用reflect.New创建一个可寻址的值。

data, err := json.Marshal(record)
require.NoError(t, err)
dst := reflect.New(reflect.TypeOf(record)) 
err = json.Unmarshal(data, dst.Interface())  // dst.Interface() is pointer to the value.
require.NoError(t, err)
require.Equal(t, record, dst.Elem().Interface()) // dst.Elem().Interface() is the value.