From 9446d22ad9196cb8ecd775817a053e1172a16b9e Mon Sep 17 00:00:00 2001 From: pzajaczkowski Date: Thu, 28 Nov 2024 15:58:31 +0100 Subject: [PATCH] Add test for `ReconnectAsync` --- .../NatsConnectionTest.cs | 39 +++++++++++++++++++ 1 file changed, 39 insertions(+) diff --git a/tests/NATS.Client.Core.Tests/NatsConnectionTest.cs b/tests/NATS.Client.Core.Tests/NatsConnectionTest.cs index 96835d6d3..da4a5c405 100644 --- a/tests/NATS.Client.Core.Tests/NatsConnectionTest.cs +++ b/tests/NATS.Client.Core.Tests/NatsConnectionTest.cs @@ -466,6 +466,45 @@ public async Task OnSocketAvailableAsync_ShouldBeInvokedOnReconnection() // Assert Assert.Equal(2, invocationCount); } + + [Fact] + public async Task ReconnectOnOpenConnection_ShouldDisconnectAndOpenNewConnection() + { + // Arrange + await using var server = NatsServer.Start(_output, _transportType); + await using var connection = server.CreateClientConnection(); + await connection.ConnectAsync(); // wait first connection open + + var openedCount = 0; + var disconnectedCount = 0; + + var openSignal = new WaitSignal(); + var disconnectSignal = new WaitSignal(); + + connection.ConnectionOpened += (_, _) => + { + Interlocked.Increment(ref openedCount); + openSignal.Pulse(); + return default; + }; + connection.ConnectionDisconnected += (_, _) => + { + Interlocked.Increment(ref disconnectedCount); + disconnectSignal.Pulse(); + return default; + }; + + // Act + await connection.ReconnectAsync(); + await disconnectSignal; + await openSignal; + + // Assert + // First connection is not taken into account, so one invocation of + // disconnected event and open connection event are expected + openedCount.ShouldBe(1); + disconnectedCount.ShouldBe(1); + } } [JsonSerializable(typeof(SampleClass))]