-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathslice_test.go
69 lines (60 loc) · 2.03 KB
/
slice_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
package gox_test
import (
"encoding/json"
"encoding/xml"
"fmt"
"os"
"testing"
"github.com/goexl/gox"
)
type UserSlice struct {
User gox.Slice[User] `json:"user,omitempty" xml:"user,omitempty"`
Users gox.Slice[User] `json:"users,omitempty" xml:"users,omitempty"`
UserPtr gox.Slice[*User] `json:"user_ptr,omitempty" xml:"user_ptr,omitempty"`
UsersPtr gox.Slice[*User] `json:"users_ptr,omitempty" xml:"users_ptr,omitempty"`
}
func receiveSlice[T any](data gox.Slice[T]) {
fmt.Println(data)
}
func receiveIntSlice(data []int) {
fmt.Println(data)
}
func TestNewSlice(t *testing.T) {
receiveSlice(gox.NewSlice(1))
receiveIntSlice(gox.NewSlice(2))
}
func TestSliceJSON(t *testing.T) {
slice := new(UserSlice)
if bytes, rfe := os.ReadFile("testdata/json/user_slice.json"); nil != rfe {
t.Errorf("读取文件内容出错,%v", rfe)
} else if ue := json.Unmarshal(bytes, slice); nil != ue {
t.Errorf("反序列化JSON出错,%v", ue)
} else {
checkUserSlice(t, slice)
}
}
func TestSliceXML(t *testing.T) {
slice := new(UserSlice)
if bytes, rfe := os.ReadFile("testdata/xml/user_slice.xml"); nil != rfe {
t.Errorf("读取文件内容出错,%v", rfe)
} else if ue := xml.Unmarshal(bytes, slice); nil != ue {
t.Errorf("反序列化XML出错,%v", ue)
} else {
// checkUserSlice(t, slice)
}
}
func checkUserSlice(t *testing.T, slice *UserSlice) {
if 1 != slice.User.Length() {
t.Error("User字段反序列化后不是只有一个元素")
} else if "storezhang" != slice.User[0].Name && 39 != slice.User[0].Age {
t.Error("User字段反序列化后字段值不正确")
} else if 1 != slice.UserPtr.Length() {
t.Error("User指针字段反序列化后不是只有一个元素")
} else if "store" != slice.UserPtr[0].Name && 19 != slice.UserPtr[0].Age {
t.Error("User指针字段反序列化后字段值不正确")
} else if 2 != slice.Users.Length() {
t.Error("Users字段反序列化后字段长度正确")
} else if 3 != slice.UsersPtr.Length() {
t.Error("Users指针字段反序列化后字段长度正确")
}
}