Skip to content

Commit

Permalink
add tests for json strict unmarshall
Browse files Browse the repository at this point in the history
  • Loading branch information
83bytes committed Jun 30, 2024
1 parent eef23f0 commit 0686520
Showing 1 changed file with 65 additions and 0 deletions.
65 changes: 65 additions & 0 deletions utils/jsonStrictUnmarshall_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
package utils

import (
"testing"
)

type Address struct {
Street string `json:"street"`
City string `json:"city"`
}

type Person struct {
Name string `json:"name"`
Age int `json:"age"`
Address Address `json:"address"`
}

func TestStrictUnmarshal(t *testing.T) {
validJSON := []byte(`{
"name": "John Doe",
"age": 30,
"address": {
"street": "123 Main St",
"city": "Anytown"
}
}`)

invalidJSON := []byte(`{
"name": "John Doe",
"age": 30,
"address": {
"street": "123 Main St",
"city": "Anytown"
},
"unknownField": "value"
}`)

// this json has an unknown field in the inner struct
invalidJSON_2 := []byte(`{
"name": "John Doe",
"age": 30,
"address": {
"street": "123 Main St",
"city": "Anytown",
"unknownInnerField": "value"
}
}`)

var person Person

err := StrictUnmarshal(validJSON, &person)
if err != nil {
t.Errorf("expected no error, got %v", err)
}

err = StrictUnmarshal(invalidJSON, &person)
if err == nil {
t.Errorf("expected error, got none")
}

err = StrictUnmarshal(invalidJSON_2, &person)
if err == nil {
t.Errorf("expected error, got none")
}
}

0 comments on commit 0686520

Please sign in to comment.