You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
88 lines
1.8 KiB
Go
88 lines
1.8 KiB
Go
3 years ago
|
package jsonx
|
||
|
|
||
|
import (
|
||
|
"strings"
|
||
|
"testing"
|
||
|
|
||
|
"github.com/stretchr/testify/assert"
|
||
|
)
|
||
|
|
||
|
func TestMarshal(t *testing.T) {
|
||
|
var v = struct {
|
||
|
Name string `json:"name"`
|
||
|
Age int `json:"age"`
|
||
|
}{
|
||
|
Name: "John",
|
||
|
Age: 30,
|
||
|
}
|
||
|
bs, err := Marshal(v)
|
||
|
assert.Nil(t, err)
|
||
|
assert.Equal(t, `{"name":"John","age":30}`, string(bs))
|
||
|
}
|
||
|
|
||
|
func TestUnmarshal(t *testing.T) {
|
||
|
const s = `{"name":"John","age":30}`
|
||
|
var v struct {
|
||
|
Name string `json:"name"`
|
||
|
Age int `json:"age"`
|
||
|
}
|
||
|
err := Unmarshal([]byte(s), &v)
|
||
|
assert.Nil(t, err)
|
||
|
assert.Equal(t, "John", v.Name)
|
||
|
assert.Equal(t, 30, v.Age)
|
||
|
}
|
||
|
|
||
|
func TestUnmarshalError(t *testing.T) {
|
||
|
const s = `{"name":"John","age":30`
|
||
|
var v struct {
|
||
|
Name string `json:"name"`
|
||
|
Age int `json:"age"`
|
||
|
}
|
||
|
err := Unmarshal([]byte(s), &v)
|
||
|
assert.NotNil(t, err)
|
||
|
}
|
||
|
|
||
|
func TestUnmarshalFromString(t *testing.T) {
|
||
|
const s = `{"name":"John","age":30}`
|
||
|
var v struct {
|
||
|
Name string `json:"name"`
|
||
|
Age int `json:"age"`
|
||
|
}
|
||
|
err := UnmarshalFromString(s, &v)
|
||
|
assert.Nil(t, err)
|
||
|
assert.Equal(t, "John", v.Name)
|
||
|
assert.Equal(t, 30, v.Age)
|
||
|
}
|
||
|
|
||
|
func TestUnmarshalFromStringError(t *testing.T) {
|
||
|
const s = `{"name":"John","age":30`
|
||
|
var v struct {
|
||
|
Name string `json:"name"`
|
||
|
Age int `json:"age"`
|
||
|
}
|
||
|
err := UnmarshalFromString(s, &v)
|
||
|
assert.NotNil(t, err)
|
||
|
}
|
||
|
|
||
|
func TestUnmarshalFromRead(t *testing.T) {
|
||
|
const s = `{"name":"John","age":30}`
|
||
|
var v struct {
|
||
|
Name string `json:"name"`
|
||
|
Age int `json:"age"`
|
||
|
}
|
||
|
err := UnmarshalFromReader(strings.NewReader(s), &v)
|
||
|
assert.Nil(t, err)
|
||
|
assert.Equal(t, "John", v.Name)
|
||
|
assert.Equal(t, 30, v.Age)
|
||
|
}
|
||
|
|
||
|
func TestUnmarshalFromReaderError(t *testing.T) {
|
||
|
const s = `{"name":"John","age":30`
|
||
|
var v struct {
|
||
|
Name string `json:"name"`
|
||
|
Age int `json:"age"`
|
||
|
}
|
||
|
err := UnmarshalFromReader(strings.NewReader(s), &v)
|
||
|
assert.NotNil(t, err)
|
||
|
}
|