TestExcludeIfEquals.cs 3.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using Topten.JsonKit;
  6. using System.IO;
  7. using System.Reflection;
  8. using Xunit;
  9. namespace TestCases
  10. {
  11. [Obfuscation(Exclude = true, ApplyToMembers = true)]
  12. public class TestExcludeIfEquals
  13. {
  14. enum Fruit
  15. {
  16. Apples,
  17. Pears,
  18. Bananas,
  19. }
  20. class Thing
  21. {
  22. [Json("boolField", ExcludeIfEquals = false)]
  23. public bool boolField;
  24. [Json("intField", ExcludeIfEquals = 0)]
  25. public int intField;
  26. [Json("boolProperty", ExcludeIfEquals = false)]
  27. public bool boolProperty { get; set; }
  28. [Json("intProperty", ExcludeIfEquals = 0)]
  29. public int intProperty { get; set; }
  30. [Json("enumField", ExcludeIfEquals = Fruit.Apples)]
  31. public Fruit enumField;
  32. [Json("enumProperty", ExcludeIfEquals = Fruit.Apples)]
  33. public Fruit enumProperty { get; set; }
  34. }
  35. public static object GetDefault(Type type)
  36. {
  37. if (type.IsValueType)
  38. {
  39. return Activator.CreateInstance(type);
  40. }
  41. return null;
  42. }
  43. [Fact]
  44. public void TestDoesntWrite()
  45. {
  46. var thing = new Thing()
  47. {
  48. boolField = false,
  49. intField = 0,
  50. boolProperty = false,
  51. intProperty = 0,
  52. enumField = Fruit.Apples,
  53. enumProperty = Fruit.Apples,
  54. };
  55. // Save it
  56. var json = Json.Format(thing);
  57. // Check the object kinds were written out
  58. Assert.DoesNotContain("\"boolField\":", json);
  59. Assert.DoesNotContain("\"intField\":", json);
  60. Assert.DoesNotContain("\"boolProperty\":", json);
  61. Assert.DoesNotContain("\"intProperty\":", json);
  62. Assert.DoesNotContain("\"enumField\":", json);
  63. Assert.DoesNotContain("\"enumProperty\":", json);
  64. }
  65. [Fact]
  66. public void TestDoesWriteNonNull()
  67. {
  68. var thing = new Thing()
  69. {
  70. boolField = true,
  71. intField = 23,
  72. boolProperty = true,
  73. intProperty = 24,
  74. enumField = Fruit.Pears,
  75. enumProperty = Fruit.Bananas,
  76. };
  77. // Save it
  78. var json = Json.Format(thing);
  79. // Check the object kinds were written out
  80. Assert.Contains("\"boolField\":", json);
  81. Assert.Contains("\"intField\":", json);
  82. Assert.Contains("\"boolProperty\":", json);
  83. Assert.Contains("\"intProperty\":", json);
  84. Assert.Contains("\"enumField\":", json);
  85. Assert.Contains("\"enumProperty\":", json);
  86. Assert.Contains("true", json);
  87. Assert.Contains("23", json);
  88. Assert.Contains("24", json);
  89. Assert.Contains("Pears", json);
  90. Assert.Contains("Bananas", json);
  91. }
  92. }
  93. }