From cf7e59a7745797b98df4757e657f553379d4bda6 Mon Sep 17 00:00:00 2001 From: Christian Kratky Date: Sat, 18 Apr 2020 16:55:37 +0200 Subject: [PATCH] Improve unit tests. --- Source/MQTTnet/Implementations/CrossPlatformSocket.cs | 9 ++++++++- Tests/MQTTnet.Core.Tests/MqttTcpChannel_Tests.cs | 4 ++-- Tests/MQTTnet.Core.Tests/Server_Tests.cs | 2 +- 3 files changed, 11 insertions(+), 4 deletions(-) diff --git a/Source/MQTTnet/Implementations/CrossPlatformSocket.cs b/Source/MQTTnet/Implementations/CrossPlatformSocket.cs index 4d7f6c9..4a8647a 100644 --- a/Source/MQTTnet/Implementations/CrossPlatformSocket.cs +++ b/Source/MQTTnet/Implementations/CrossPlatformSocket.cs @@ -10,6 +10,8 @@ namespace MQTTnet.Implementations { readonly Socket _socket; + NetworkStream _networkStream; + public CrossPlatformSocket(AddressFamily addressFamily) { _socket = new Socket(addressFamily, SocketType.Stream, ProtocolType.Tcp); @@ -137,6 +139,8 @@ namespace MQTTnet.Implementations try { + _networkStream?.Dispose(); + // Workaround for: workaround for https://github.com/dotnet/corefx/issues/24430 using (cancellationToken.Register(() => _socket.Dispose())) { @@ -148,6 +152,8 @@ namespace MQTTnet.Implementations await _socket.ConnectAsync(host, port).ConfigureAwait(false); #endif } + + _networkStream = new NetworkStream(_socket, true); } catch (ObjectDisposedException) { @@ -190,11 +196,12 @@ namespace MQTTnet.Implementations public NetworkStream GetStream() { - return new NetworkStream(_socket, true); + return _networkStream; } public void Dispose() { + _networkStream?.Dispose(); _socket?.Dispose(); } diff --git a/Tests/MQTTnet.Core.Tests/MqttTcpChannel_Tests.cs b/Tests/MQTTnet.Core.Tests/MqttTcpChannel_Tests.cs index 6e78dec..4965da2 100644 --- a/Tests/MQTTnet.Core.Tests/MqttTcpChannel_Tests.cs +++ b/Tests/MQTTnet.Core.Tests/MqttTcpChannel_Tests.cs @@ -37,10 +37,10 @@ namespace MQTTnet.Tests var clientSocket = new CrossPlatformSocket(AddressFamily.InterNetwork); await clientSocket.ConnectAsync("localhost", 50001, CancellationToken.None); - await Task.Delay(100, ct.Token); - var tcpChannel = new MqttTcpChannel(clientSocket.GetStream(), "test", null); + await Task.Delay(100, ct.Token); + var buffer = new byte[1]; await tcpChannel.ReadAsync(buffer, 0, 1, ct.Token); diff --git a/Tests/MQTTnet.Core.Tests/Server_Tests.cs b/Tests/MQTTnet.Core.Tests/Server_Tests.cs index ed22a56..c2256a6 100644 --- a/Tests/MQTTnet.Core.Tests/Server_Tests.cs +++ b/Tests/MQTTnet.Core.Tests/Server_Tests.cs @@ -375,7 +375,7 @@ namespace MQTTnet.Tests await c1.PublishAsync(message); } - await Task.Delay(500); + await Task.Delay(3000); Assert.AreEqual(2000, receivedMessagesCount); }