Skip to content

Commit efcfcb4

Browse files
author
Niel de Wet
committed
feat: fix validation not returning errors
1 parent 1a752d6 commit efcfcb4

File tree

2 files changed

+33
-7
lines changed

2 files changed

+33
-7
lines changed

src/HttpClientSettings/Extensions/ServiceCollectionExtensions.cs

+18-7
Original file line numberDiff line numberDiff line change
@@ -10,17 +10,28 @@ public static IServiceCollection AddHttpClientSettings(this IServiceCollection s
1010
{
1111
var section = configuration.GetRequiredSection(Constants.AppSettings.SectionName);
1212

13-
services.Configure<HttpClientAppSettings>(section)
14-
.PostConfigure<HttpClientAppSettings>(config =>
13+
services.AddOptions<HttpClientAppSettings>()
14+
.Bind(section)
15+
.Validate(httpClientAppSettings =>
1516
{
16-
if (validateSettings)
17-
{
18-
var validator = new HttpClientAppSettingsValidator(config);
19-
validator.Validate();
20-
}
17+
if (validateSettings) ValidateHttpClientAppSettings(httpClientAppSettings);
18+
19+
return true;
2120
});
2221

2322
return services;
2423
}
24+
25+
internal static void ValidateHttpClientAppSettings(HttpClientAppSettings httpClientAppSettings)
26+
{
27+
var validator = new HttpClientAppSettingsValidator(httpClientAppSettings);
28+
29+
var validationResponse = validator.Validate();
30+
31+
if (!validationResponse.IsSuccess)
32+
{
33+
throw new InvalidAppSettingsException(validationResponse.Errors);
34+
}
35+
}
2536
}
2637
}

test/HttpClientSettings.Tests/Extensions/ServiceCollectionExtensionsTests.cs

+15
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,8 @@ namespace HttpClientSettings.Tests.Extensions;
55

66
public class ServiceCollectionExtensionsTests
77
{
8+
private readonly HttpClientAppSettings _settings = new();
9+
810
[Fact]
911
public void AddHttpClientSettings_ShouldAddSettingsToConfig()
1012
{
@@ -15,4 +17,17 @@ public void AddHttpClientSettings_ShouldAddSettingsToConfig()
1517

1618
services.Received().Configure<HttpClientAppSettings>(config);
1719
}
20+
21+
[Fact]
22+
public void ValidateHttpClientAppSettings_GivenInvalidAppSettings_ShouldThrowException()
23+
{
24+
var clients = Builder<HttpClientSetting>.CreateListOfSize(1)
25+
.All()
26+
.With(x => x.Name, "")
27+
.Build();
28+
29+
_settings.LoadClientsForUnitTesting(clients);
30+
31+
Assert.Throws<InvalidAppSettingsException>(() => ServiceCollectionExtensions.ValidateHttpClientAppSettings(_settings));
32+
}
1833
}

0 commit comments

Comments
 (0)