naming_strategy_test.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. package extra
  2. import (
  3. "github.com/json-iterator/go"
  4. "github.com/stretchr/testify/require"
  5. "testing"
  6. )
  7. func Test_lower_case_with_underscores(t *testing.T) {
  8. should := require.New(t)
  9. should.Equal("hello_world", LowerCaseWithUnderscores("helloWorld"))
  10. should.Equal("hello_world", LowerCaseWithUnderscores("HelloWorld"))
  11. SetNamingStrategy(LowerCaseWithUnderscores)
  12. output, err := jsoniter.Marshal(struct {
  13. UserName string
  14. FirstLanguage string
  15. }{
  16. UserName: "taowen",
  17. FirstLanguage: "Chinese",
  18. })
  19. should.Nil(err)
  20. should.Equal(`{"user_name":"taowen","first_language":"Chinese"}`, string(output))
  21. }
  22. func Test_set_naming_strategy_with_overrides(t *testing.T) {
  23. should := require.New(t)
  24. SetNamingStrategy(LowerCaseWithUnderscores)
  25. output, err := jsoniter.Marshal(struct {
  26. UserName string `json:"UserName"`
  27. FirstLanguage string
  28. }{
  29. UserName: "taowen",
  30. FirstLanguage: "Chinese",
  31. })
  32. should.Nil(err)
  33. should.Equal(`{"UserName":"taowen","first_language":"Chinese"}`, string(output))
  34. }
  35. func Test_set_naming_strategy_with_omitempty(t *testing.T) {
  36. should := require.New(t)
  37. SetNamingStrategy(LowerCaseWithUnderscores)
  38. output, err := jsoniter.Marshal(struct {
  39. UserName string
  40. FirstLanguage string `json:",omitempty"`
  41. }{
  42. UserName: "taowen",
  43. })
  44. should.Nil(err)
  45. should.Equal(`{"user_name":"taowen"}`, string(output))
  46. }
  47. func Test_set_naming_strategy_with_private_field(t *testing.T) {
  48. should := require.New(t)
  49. SetNamingStrategy(LowerCaseWithUnderscores)
  50. output, err := jsoniter.Marshal(struct {
  51. UserName string
  52. userId int
  53. _UserAge int
  54. }{
  55. UserName: "allen",
  56. userId: 100,
  57. _UserAge: 30,
  58. })
  59. should.Nil(err)
  60. should.Equal(`{"user_name":"allen"}`, string(output))
  61. }