-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
add tests for json strict unmarshall
- Loading branch information
Showing
1 changed file
with
65 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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") | ||
} | ||
} |