Skip to content

Commit cd17f88

Browse files
authored
Added IAsyncDisposable to TestServiceProvider (#292)
1 parent 51d6b81 commit cd17f88

File tree

4 files changed

+40
-3
lines changed

4 files changed

+40
-3
lines changed

CHANGELOG.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -98,6 +98,8 @@ List of new features.
9898

9999
By [@egil](https://github.com/egil) in [#288](https://github.com/egil/bUnit/pull/288).
100100

101+
- Added support for registering services in bUnits `Services` collection that implements `IAsyncDisposable`. Suggested by [@jmaillet](https://github.com/jmaillet) in [#249](https://github.com/egil/bUnit/issues/249).
102+
101103
### Changed
102104
List of changes in existing functionality.
103105

src/bunit.core/TestServiceProvider.cs

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ public sealed class TestServiceProvider : IServiceProvider, IServiceCollection,
1313
{
1414
private readonly IServiceCollection _serviceCollection;
1515
private ServiceProvider? _serviceProvider;
16-
16+
1717
/// <summary>
1818
/// Gets whether this <see cref="TestServiceProvider"/> has been initialized, and
1919
/// no longer will accept calls to the <c>AddService</c>'s methods.
@@ -78,7 +78,14 @@ public object GetService(Type serviceType)
7878
/// <inheritdoc/>
7979
public void Dispose()
8080
{
81-
_serviceProvider?.Dispose();
81+
if (_serviceProvider is null) return;
82+
83+
var disposedTask = _serviceProvider.DisposeAsync().AsTask();
84+
85+
if (!disposedTask.IsCompleted)
86+
disposedTask.GetAwaiter().GetResult();
87+
88+
_serviceProvider.Dispose();
8289
}
8390

8491
/// <inheritdoc/>

tests/bunit.core.tests/TestServiceProviderTest.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@
77

88
namespace Bunit
99
{
10-
public class TestServiceProviderTest
10+
public partial class TestServiceProviderTest
1111
{
1212
class DummyService { }
1313
class AnotherDummyService { }
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
#if NET5_0
2+
using System;
3+
using System.Threading.Tasks;
4+
using Microsoft.Extensions.DependencyInjection;
5+
using Shouldly;
6+
using Xunit;
7+
8+
namespace Bunit
9+
{
10+
public partial class TestServiceProviderTest
11+
{
12+
[Fact(DisplayName = "Can correctly dispose of async disposable service")]
13+
public void Net5Test001()
14+
{
15+
var sut = new TestServiceProvider();
16+
sut.AddScoped<AsyncDisposableService>();
17+
sut.GetService<AsyncDisposableService>();
18+
19+
Should.NotThrow(() => sut.Dispose());
20+
}
21+
22+
class AsyncDisposableService : IAsyncDisposable
23+
{
24+
public ValueTask DisposeAsync() => ValueTask.CompletedTask;
25+
}
26+
}
27+
}
28+
#endif

0 commit comments

Comments
 (0)