CfgRootExtensionsTests.cs 2.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. namespace Apq.Cfg.Tests;
  2. /// <summary>
  3. /// CfgRootExtensions 扩展方法测试
  4. /// </summary>
  5. public class CfgRootExtensionsTests : IDisposable
  6. {
  7. private readonly string _testDir;
  8. public CfgRootExtensionsTests()
  9. {
  10. _testDir = Path.Combine(Path.GetTempPath(), $"ApqCfgTests_{Guid.NewGuid():N}");
  11. Directory.CreateDirectory(_testDir);
  12. }
  13. public void Dispose()
  14. {
  15. if (Directory.Exists(_testDir))
  16. {
  17. Directory.Delete(_testDir, true);
  18. }
  19. }
  20. [Fact]
  21. public void TryGet_ExistingKey_ReturnsTrueAndValue()
  22. {
  23. // Arrange
  24. var jsonPath = Path.Combine(_testDir, "config.json");
  25. File.WriteAllText(jsonPath, """{"IntValue": 42, "StringValue": "Hello"}""");
  26. using var cfg = new CfgBuilder()
  27. .AddJson(jsonPath, level: 0, writeable: false)
  28. .Build();
  29. // Act & Assert
  30. Assert.True(cfg.TryGet<int>("IntValue", out var intValue));
  31. Assert.Equal(42, intValue);
  32. Assert.True(cfg.TryGet<string>("StringValue", out var stringValue));
  33. Assert.Equal("Hello", stringValue);
  34. }
  35. [Fact]
  36. public void TryGet_NonExistingKey_ReturnsFalseAndDefault()
  37. {
  38. // Arrange
  39. var jsonPath = Path.Combine(_testDir, "config.json");
  40. File.WriteAllText(jsonPath, """{"Key": "Value"}""");
  41. using var cfg = new CfgBuilder()
  42. .AddJson(jsonPath, level: 0, writeable: false)
  43. .Build();
  44. // Act & Assert
  45. Assert.False(cfg.TryGet<int>("NonExistent", out var intValue));
  46. Assert.Equal(default, intValue);
  47. Assert.False(cfg.TryGet<string>("NonExistent", out var stringValue));
  48. Assert.Null(stringValue);
  49. }
  50. [Fact]
  51. public void GetRequired_ExistingKey_ReturnsValue()
  52. {
  53. // Arrange
  54. var jsonPath = Path.Combine(_testDir, "config.json");
  55. File.WriteAllText(jsonPath, """{"RequiredInt": 100, "RequiredString": "Required"}""");
  56. using var cfg = new CfgBuilder()
  57. .AddJson(jsonPath, level: 0, writeable: false)
  58. .Build();
  59. // Act & Assert
  60. Assert.Equal(100, cfg.GetRequired<int>("RequiredInt"));
  61. Assert.Equal("Required", cfg.GetRequired<string>("RequiredString"));
  62. }
  63. [Fact]
  64. public void GetRequired_NonExistingKey_ThrowsException()
  65. {
  66. // Arrange
  67. var jsonPath = Path.Combine(_testDir, "config.json");
  68. File.WriteAllText(jsonPath, """{"Key": "Value"}""");
  69. using var cfg = new CfgBuilder()
  70. .AddJson(jsonPath, level: 0, writeable: false)
  71. .Build();
  72. // Act & Assert
  73. var ex = Assert.Throws<InvalidOperationException>(() => cfg.GetRequired<string>("NonExistent"));
  74. Assert.Contains("NonExistent", ex.Message);
  75. }
  76. }