...
1 package tests
2
3 import (
4 "fmt"
5 "reflect"
6 "testing"
7 )
8
9 func TestRequiredField(t *testing.T) {
10 cases := []struct{ json, errorMessage string }{
11 {`{"first_name":"Foo", "last_name": "Bar"}`, ""},
12 {`{"last_name":"Bar"}`, "key 'first_name' is required"},
13 {"{}", "key 'first_name' is required"},
14 }
15
16 for _, tc := range cases {
17 var v RequiredOptionalStruct
18 err := v.UnmarshalJSON([]byte(tc.json))
19 if tc.errorMessage == "" {
20 if err != nil {
21 t.Errorf("%s. UnmarshalJSON didn`t expect error: %v", tc.json, err)
22 }
23 } else {
24 if fmt.Sprintf("%v", err) != tc.errorMessage {
25 t.Errorf("%s. UnmarshalJSON expected error: %v. got: %v", tc.json, tc.errorMessage, err)
26 }
27 }
28 }
29 }
30
31 func TestRequiredOptionalMap(t *testing.T) {
32 baseJson := `{"req_map":{}, "oe_map":{}, "noe_map":{}, "oe_slice":[]}`
33 wantDecoding := RequiredOptionalMap{MapIntString{}, nil, MapIntString{}}
34
35 var v RequiredOptionalMap
36 if err := v.UnmarshalJSON([]byte(baseJson)); err != nil {
37 t.Errorf("%s. UnmarshalJSON didn't expect error: %v", baseJson, err)
38 }
39 if !reflect.DeepEqual(v, wantDecoding) {
40 t.Errorf("%s. UnmarshalJSON expected to gen: %v. got: %v", baseJson, wantDecoding, v)
41 }
42
43 baseStruct := RequiredOptionalMap{MapIntString{}, MapIntString{}, MapIntString{}}
44 wantJson := `{"req_map":{},"noe_map":{}}`
45 data, err := baseStruct.MarshalJSON()
46 if err != nil {
47 t.Errorf("MarshalJSON didn't expect error: %v on %v", err, data)
48 } else if string(data) != wantJson {
49 t.Errorf("%v. MarshalJSON wanted: %s got %s", baseStruct, wantJson, string(data))
50 }
51 }
52
View as plain text