ColorJsonConverterTests.cs 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. using System;
  2. using System.IO;
  3. using System.Text;
  4. using System.Text.Json;
  5. using Microsoft.Xna.Framework;
  6. using MonoGame.Extended.Serialization.Json;
  7. namespace MonoGame.Extended.Tests.Serialization;
  8. public sealed class ColorJsonConverterTests
  9. {
  10. private readonly ColorJsonConverter _converter = new ColorJsonConverter();
  11. [Fact]
  12. public void CanConvert_ColorType_ReturnsTrue()
  13. {
  14. var colorType = typeof(Color);
  15. var result = _converter.CanConvert(colorType);
  16. Assert.True(result);
  17. }
  18. [Fact]
  19. public void CanConvert_NonColorType_ReturnsFalse()
  20. {
  21. var otherType = typeof(string);
  22. var result = _converter.CanConvert(otherType);
  23. Assert.False(result);
  24. }
  25. [Theory]
  26. [InlineData("Red", 255, 0, 0, 255)]
  27. [InlineData("#FF0000FF", 255, 0, 0, 255)]
  28. public void Read_ValidColorJson_ReturnsExpectedColor(string jsonValue, byte r, byte g, byte b, byte a)
  29. {
  30. var json = $"\"{jsonValue}\"";
  31. var reader = new Utf8JsonReader(Encoding.UTF8.GetBytes(json));
  32. reader.Read();
  33. var actual = _converter.Read(ref reader, typeof(Color), new JsonSerializerOptions());
  34. var expected = new Color(r, g, b, a);
  35. Assert.Equal(expected, actual);
  36. }
  37. [Fact]
  38. public void Write_ValidColor_WritesExpectedJson()
  39. {
  40. var expected = "#ff000000";
  41. var color = ColorHelper.FromHex(expected);
  42. using var stream = new MemoryStream();
  43. using var writer = new Utf8JsonWriter(stream);
  44. _converter.Write(writer, color, new JsonSerializerOptions());
  45. writer.Flush();
  46. var actual = Encoding.UTF8.GetString(stream.ToArray());
  47. Assert.Equal($"\"{expected}\"", actual);
  48. }
  49. [Fact]
  50. public void Write_NullWrier_ThrowArgumentNullException()
  51. {
  52. var color = Color.DarkOrange;
  53. Assert.Throws<ArgumentNullException>(() => _converter.Write(null, color, new JsonSerializerOptions()));
  54. }
  55. }