1313namespace AzureEventGridSimulator . Tests . UnitTests . Retry ;
1414
1515[ Trait ( "Category" , "unit" ) ]
16- public class HttpEventDeliveryServiceTests
16+ public class HttpEventDeliveryServiceTests : IDisposable
1717{
1818 private readonly EventSchemaFormatterFactory _formatterFactory ;
19+ private readonly List < HttpClient > _httpClients = [ ] ;
1920 private readonly ILogger < HttpEventDeliveryService > _logger ;
2021
2122 public HttpEventDeliveryServiceTests ( )
@@ -27,6 +28,16 @@ public HttpEventDeliveryServiceTests()
2728 ) ;
2829 }
2930
31+ public void Dispose ( )
32+ {
33+ foreach ( var client in _httpClients )
34+ {
35+ client . Dispose ( ) ;
36+ }
37+
38+ _httpClients . Clear ( ) ;
39+ }
40+
3041 [ Theory ]
3142 [ InlineData ( HttpStatusCode . OK ) ]
3243 [ InlineData ( HttpStatusCode . Created ) ]
@@ -194,7 +205,7 @@ public async Task GivenDnsError_WhenDelivering_ThenReturnsNetworkError()
194205 result . ErrorMessage . ShouldContain ( "No such host" ) ;
195206 }
196207
197- private static IHttpClientFactory CreateMockHttpClientFactory (
208+ private IHttpClientFactory CreateMockHttpClientFactory (
198209 HttpStatusCode statusCode = HttpStatusCode . OK ,
199210 Exception throwException = null ,
200211 Action responseAction = null ,
@@ -208,6 +219,7 @@ private static IHttpClientFactory CreateMockHttpClientFactory(
208219 captureHeaders
209220 ) ;
210221 var httpClient = new HttpClient ( handler ) ;
222+ _httpClients . Add ( httpClient ) ;
211223
212224 var factory = Substitute . For < IHttpClientFactory > ( ) ;
213225 factory . CreateClient ( Arg . Any < string > ( ) ) . Returns ( httpClient ) ;
@@ -264,6 +276,7 @@ private class MockHttpMessageHandler : HttpMessageHandler
264276 private readonly Action < HttpRequestHeaders > _captureHeaders ;
265277 private readonly Exception _exception ;
266278 private readonly Action _responseAction ;
279+ private readonly List < HttpResponseMessage > _responses = [ ] ;
267280 private readonly HttpStatusCode _statusCode ;
268281
269282 public MockHttpMessageHandler (
@@ -292,13 +305,29 @@ CancellationToken cancellationToken
292305 throw _exception ;
293306 }
294307
295- return Task . FromResult (
296- new HttpResponseMessage ( _statusCode )
308+ var response = new HttpResponseMessage ( _statusCode )
309+ {
310+ Content = new StringContent ( "" ) ,
311+ ReasonPhrase = _statusCode . ToString ( ) ,
312+ } ;
313+ _responses . Add ( response ) ;
314+
315+ return Task . FromResult ( response ) ;
316+ }
317+
318+ protected override void Dispose ( bool disposing )
319+ {
320+ if ( disposing )
321+ {
322+ foreach ( var response in _responses )
297323 {
298- Content = new StringContent ( "" ) ,
299- ReasonPhrase = _statusCode . ToString ( ) ,
324+ response . Dispose ( ) ;
300325 }
301- ) ;
326+
327+ _responses . Clear ( ) ;
328+ }
329+
330+ base . Dispose ( disposing ) ;
302331 }
303332 }
304333}
0 commit comments