namespace WebApi.Test.Application; /// /// ConfigApplication 单元测试 /// public class ConfigApplicationTest : BaseApplicationTest { private readonly IConfigService _configService; private readonly ILogger _logger; private readonly ConfigApplication _application; public ConfigApplicationTest() { _configService = Substitute.For(); _logger = CreateMockLogger(); _application = new ConfigApplication(_configService, _logger); } #region GetConfigAsync Tests [Fact] public async Task GetConfigAsync_有效Key_应返回配置值() { // Arrange const string key = "test-key"; const string expectedValue = "test-value"; _configService.GetConfigByKeyAsync(key).Returns(expectedValue); // Act var result = await _application.GetConfigAsync(key); // Assert result.Should().Be(expectedValue); await _configService.Received(1).GetConfigByKeyAsync(key); } [Fact] public async Task GetConfigAsync_配置不存在_应返回空字符串() { // Arrange const string key = "non-existent-key"; _configService.GetConfigByKeyAsync(key).Returns((string?)null); // Act var result = await _application.GetConfigAsync(key); // Assert result.Should().BeEmpty(); } [Fact] public async Task GetConfigAsync_空Key_应抛出ValidationException() { // Arrange & Act & Assert await Assert.ThrowsAsync(() => _application.GetConfigAsync(string.Empty)); } [Fact] public async Task GetConfigAsync_空白Key_应抛出ValidationException() { // Arrange & Act & Assert await Assert.ThrowsAsync(() => _application.GetConfigAsync(" ")); } #endregion #region SetConfigAsync Tests [Fact] public async Task SetConfigAsync_有效参数_应成功设置() { // Arrange const string key = "test-key"; const string value = "test-value"; _configService.SetConfigByKeyAsync(key, value).Returns(true); // Act await _application.SetConfigAsync(key, value); // Assert await _configService.Received(1).SetConfigByKeyAsync(key, value); } [Fact] public async Task SetConfigAsync_空Key_应抛出ValidationException() { // Arrange & Act & Assert await Assert.ThrowsAsync(() => _application.SetConfigAsync(string.Empty, "value")); } [Fact] public async Task SetConfigAsync_设置失败_应抛出BusinessException() { // Arrange const string key = "test-key"; const string value = "test-value"; _configService.SetConfigByKeyAsync(key, value).Returns(false); // Act & Assert var exception = await Assert.ThrowsAsync(() => _application.SetConfigAsync(key, value)); exception.Message.Should().Contain(key); } [Fact] public async Task SetConfigAsync_成功设置_应记录日志() { // Arrange const string key = "test-key"; const string value = "test-value"; _configService.SetConfigByKeyAsync(key, value).Returns(true); // Act await _application.SetConfigAsync(key, value); // Assert _logger.Received().Log( LogLevel.Information, Arg.Any(), Arg.Is(o => o.ToString()!.Contains(key)), Arg.Any(), Arg.Any>()! ); } #endregion }