diff --git a/DiscordPlayerCountBot.Tests/JsonTests.cs b/DiscordPlayerCountBot.Tests/JsonTests.cs new file mode 100644 index 0000000..8dd2ec2 --- /dev/null +++ b/DiscordPlayerCountBot.Tests/JsonTests.cs @@ -0,0 +1,69 @@ +using DiscordPlayerCountBot.Json; + +namespace DiscordPlayerCountBot.Tests; + +[Collection("Json Serialization Test Suite")] +public class JsonTests +{ + [Fact(DisplayName = "Test Primitives Float", Timeout = 30)] + public void SerializePrimitivesFloat() + { + var testFloat = JsonHelper.DeserializeObject("2.23"); + + Assert.True(testFloat == (float)2.23, $"{testFloat}"); + Assert.True(testFloat.GetType() == typeof(float)); + } + + [Fact(DisplayName = "Test Primitives Double", Timeout = 30)] + public void SerializePrimitivesDouble() + { + var testDouble = JsonHelper.DeserializeObject("200.00"); + + Assert.True(testDouble == 200.00); + Assert.True(testDouble.GetType() == typeof(double)); + + } + + [Fact(DisplayName = "Test Primitives Char", Timeout = 30)] + public void SerializePrimitivesChar() + { + var testChar = JsonHelper.DeserializeObject("3"); + + Assert.True(testChar == '3'); + Assert.True(testChar.GetType() == typeof(char)); + } + + [Fact(DisplayName = "Test Primitives Bool", Timeout = 30)] + public void SerializePrimitivesBool() + { + var testBooleanTrue = JsonHelper.DeserializeObject("true"); + + Assert.True(testBooleanTrue); + Assert.True(testBooleanTrue.GetType() == typeof(bool)); + + var testBooleanFalse = JsonHelper.DeserializeObject("false"); + + Assert.True(!testBooleanFalse); + Assert.True(testBooleanFalse.GetType() == typeof(bool)); + } + + [Fact(DisplayName = "Test Primitives Int", Timeout = 30)] + public void SerializePrimitivesInt() + { + var testInt = JsonHelper.DeserializeObject("100"); + + Assert.True(testInt == 100); + Assert.True(testInt.GetType() == typeof(int)); + } + + [Fact(DisplayName = "Test Strings", Timeout = 30)] + public void SerializeStrings() + { + var testString = JsonHelper.DeserializeObject("test") ?? ""; + + Assert.True(!string.IsNullOrEmpty(testString), "Should not be null or empty."); + Assert.True(!string.IsNullOrWhiteSpace(testString), "Should not be null or whitespace."); + Assert.Equal("test", testString, true, true, true); + Assert.True(testString.GetType() == typeof(string)); + } +} \ No newline at end of file diff --git a/DiscordPlayerCountBot/Json/JsonHelper.cs b/DiscordPlayerCountBot/Json/JsonHelper.cs index f150aae..116c72b 100644 --- a/DiscordPlayerCountBot/Json/JsonHelper.cs +++ b/DiscordPlayerCountBot/Json/JsonHelper.cs @@ -1,4 +1,5 @@ using Newtonsoft.Json; +using System; namespace DiscordPlayerCountBot.Json { @@ -6,6 +7,8 @@ public static class JsonHelper { public static T? DeserializeObject(string content) { + if (typeof(T).IsPrimitive || typeof(T) == typeof(string)) return (T)Convert.ChangeType(content, typeof(T)); + return JsonConvert.DeserializeObject(content, new JsonSerializerSettings() { NullValueHandling = NullValueHandling.Ignore