整理代码结构, 增加普通结构体单元测试
This commit is contained in:
@ -9,19 +9,14 @@ package dynamicstruct
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"reflect"
|
||||
"testing"
|
||||
|
||||
. "github.com/smartystreets/goconvey/convey"
|
||||
)
|
||||
|
||||
func Test_dynamicStructImpl_New(t *testing.T) {
|
||||
/*func Test_dynamicStructImpl_New(t *testing.T) {
|
||||
instance := NewStruct(map[string]string{}).
|
||||
/*AddField("Integer", "", 0, `json:"int"`, false).
|
||||
AddField("Text", "", "", `json:"someText"`, false).
|
||||
AddField("Float", "", 0.0, `json:"double"`, false).
|
||||
AddField("Boolean", "", false, "", false).
|
||||
AddField("Slice", "", []int{}, "", false).
|
||||
AddField("Anonymous", "", "", `json:"-"`, false).*/
|
||||
AddField("user.base.age", "", 20, `json:"age"`, false).
|
||||
AddField("user.base.name", "", "", `json:"name"`, false).
|
||||
AddField("user.job.address", "", "", `json:"address"`, false).
|
||||
@ -52,3 +47,50 @@ func Test_dynamicStructImpl_New(t *testing.T) {
|
||||
fmt.Println(string(valByte))
|
||||
// fmt.Println(reflect.ValueOf(val).Elem().FieldByName("Integer").Interface())
|
||||
}
|
||||
*/
|
||||
// TestStruct : 测试结构体
|
||||
func TestStruct(t *testing.T) {
|
||||
Convey("普通结构体,无嵌套", t, func() {
|
||||
data := []byte(`
|
||||
{
|
||||
"age": 123,
|
||||
"name": "example",
|
||||
"double": 123.45,
|
||||
"tag_map": "ttt",
|
||||
"bool": true,
|
||||
"slice": [1, 2, 3]
|
||||
}
|
||||
`)
|
||||
instance := NewStruct(map[string]string{
|
||||
"test_tag_map": `json:"tag_map"`,
|
||||
}).
|
||||
AddField("age", "", 0, `json:"age"`, false).
|
||||
AddField("name", "", "", `json:"name"`, false).
|
||||
AddField("test_tag_map", "", "", "", false).
|
||||
AddField("double", "", 0.0, `json:"double"`, false).
|
||||
AddField("bool", "", false, "", false).
|
||||
AddField("slice", "", []int{}, `json:"slice"`, false).Build()
|
||||
val := instance.New()
|
||||
err := json.Unmarshal(data, &val)
|
||||
So(err, ShouldBeNil)
|
||||
reflectType := reflect.TypeOf(val)
|
||||
// 需要是结构体类型
|
||||
So(reflectType.Elem().Kind(), ShouldEqual, reflect.Struct)
|
||||
// 验证数据
|
||||
// 数据序列化成功
|
||||
targetByte, targetErr := json.Marshal(val)
|
||||
So(targetErr, ShouldBeNil)
|
||||
// 数据转map成功
|
||||
var res map[string]any
|
||||
targetUnmarshalErr := json.Unmarshal(targetByte, &res)
|
||||
So(targetUnmarshalErr, ShouldBeNil)
|
||||
// 验证数据
|
||||
So(len(res), ShouldEqual, 6)
|
||||
So(res["age"], ShouldEqual, float64(123))
|
||||
So(res["name"], ShouldEqual, "example")
|
||||
So(res["tag_map"], ShouldEqual, "ttt")
|
||||
So(res["double"], ShouldEqual, 123.45)
|
||||
So(res["bool"], ShouldEqual, true)
|
||||
So(res["slice"], ShouldEqual, []any{float64(1), float64(2), float64(3)})
|
||||
})
|
||||
}
|
||||
|
Reference in New Issue
Block a user