summaryrefslogtreecommitdiff
path: root/optional/json_test.go
blob: 132dea28b6735fe9207f77e42af18c1a29bc1cb0 (plain)
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
package optional_test

import (
	"encoding/json"
	"testing"

	"xengineering.eu/optional-go/optional"
)

func TestUnmarshal(t *testing.T) {
	text := `{"something": null}`

	var Buffer struct {
		Something optional.Optional[bool]
	}

	err := json.Unmarshal([]byte(text), &Buffer)
	if err != nil {
		t.Fatal(err)
	}

	if Buffer.Something.Value != false {
		t.Fatal("Value of member set to 'null' is not default value.")
	}

	if Buffer.Something.Exists == true {
		t.Fatal("Member set to 'null' but Optional claims that it exists.")
	}
}

func TestMarshal(t *testing.T) {
	Buffer := struct {
		Something optional.Optional[bool] `json:"something"`
	}{
		Something: optional.Optional[bool]{
			Value:  false,
			Exists: false,
		},
	}

	result, err := json.Marshal(Buffer)
	if err != nil {
		t.Fatal(err)
	}

	expectation := `{"something":null}`

	if string(result) != expectation {
		t.Fatalf(
			"Expected '%s' but marshalled '%s'\n",
			expectation,
			string(result),
		)
	}
}