Skip to content

Commit e14ab39

Browse files
authored
fix: Adding Async Lifetime method to fix flaky unit tests (#333)
<!-- Please use this template for your pull request. --> <!-- Please use the sections that you need and delete other sections --> ## This PR <!-- add the description of the PR here --> - Changes the way we currently reset the Api between unit tests. This approach should be safer since it calls the official `Shutdown`, and when we call the API again, all the resources are reset. ### Notes <!-- any additional notes for this PR --> Check for more details: https://xunit.net/docs/shared-context#:~:text=For%20context%20cleanup%2C%20add%20the%20IDisposable%20interface%20to,call%20IAsyncDisposable%20%28it%20is%20planned%20for%20xUnit%20v3%29. --------- Signed-off-by: André Silva <[email protected]>
1 parent b9ebddf commit e14ab39

File tree

2 files changed

+21
-7
lines changed

2 files changed

+21
-7
lines changed

src/OpenFeature/Api.cs

+9-1
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,7 @@ public sealed class Api : IEventBus
2929
/// <summary>
3030
/// Singleton instance of Api
3131
/// </summary>
32-
public static Api Instance { get; } = new Api();
32+
public static Api Instance { get; private set; } = new Api();
3333

3434
// Explicit static constructor to tell C# compiler
3535
// not to mark type as beforeFieldInit
@@ -300,5 +300,13 @@ private async Task AfterError(FeatureProvider provider, Exception? ex)
300300

301301
await this._eventExecutor.EventChannel.Writer.WriteAsync(new Event { Provider = provider, EventPayload = eventPayload }).ConfigureAwait(false);
302302
}
303+
304+
/// <summary>
305+
/// This method should only be using for testing purposes. It will reset the singleton instance of the API.
306+
/// </summary>
307+
internal static void ResetApi()
308+
{
309+
Instance = new Api();
310+
}
303311
}
304312
}
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,20 @@
1-
using System;
1+
using System.Threading.Tasks;
2+
using Xunit;
23

34
namespace OpenFeature.Tests;
45

5-
public class ClearOpenFeatureInstanceFixture : IDisposable
6+
public class ClearOpenFeatureInstanceFixture : IAsyncLifetime
67
{
8+
public Task InitializeAsync()
9+
{
10+
Api.ResetApi();
11+
12+
return Task.CompletedTask;
13+
}
14+
715
// Make sure the singleton is cleared between tests
8-
public void Dispose()
16+
public async Task DisposeAsync()
917
{
10-
Api.Instance.SetContext(null);
11-
Api.Instance.ClearHooks();
12-
Api.Instance.SetProviderAsync(new NoOpFeatureProvider()).Wait();
18+
await Api.Instance.ShutdownAsync().ConfigureAwait(false);
1319
}
1420
}

0 commit comments

Comments
 (0)