summaryrefslogtreecommitdiff
path: root/optional/json_test.go
diff options
context:
space:
mode:
authorxengineering <me@xengineering.eu>2024-11-08 18:21:09 +0100
committerxengineering <me@xengineering.eu>2024-11-08 18:21:09 +0100
commitd8dbdaedcfb9099ae091a805972d380a7cddc4a4 (patch)
treeed5965bcdeed0c395604a7a46095d8c09a0f396b /optional/json_test.go
parent08ea24952ece9c82a932910126975d26e486758c (diff)
downloadoptional-go-d8dbdaedcfb9099ae091a805972d380a7cddc4a4.tar
optional-go-d8dbdaedcfb9099ae091a805972d380a7cddc4a4.tar.zst
optional-go-d8dbdaedcfb9099ae091a805972d380a7cddc4a4.zip
Add json (un)marshal supportv1.0.0
This allows to use optionals for fields of structs which are marshalled or unmarshalled to or from JavaScript object notation (JSON).
Diffstat (limited to 'optional/json_test.go')
-rw-r--r--optional/json_test.go55
1 files changed, 55 insertions, 0 deletions
diff --git a/optional/json_test.go b/optional/json_test.go
new file mode 100644
index 0000000..132dea2
--- /dev/null
+++ b/optional/json_test.go
@@ -0,0 +1,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),
+ )
+ }
+}