Skip to content

Commit b821124

Browse files
committed
Remove reflection from Connect test
This removes the reflection from the double connection test and replaces it with a `MockHttpHandler` to let the connection actually succeed and then test the redundant `ConnectAsync` call. partial fix for #48
1 parent 10c712a commit b821124

File tree

1 file changed

+44
-2
lines changed

1 file changed

+44
-2
lines changed

tests/ModelContextProtocol.Tests/Transport/SseClientTransportTests.cs

Lines changed: 44 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
using ModelContextProtocol.Tests.Utils;
66
using System.Net;
77
using System.Reflection;
8+
using System.Reflection.Metadata;
89

910
namespace ModelContextProtocol.Tests.Transport;
1011

@@ -107,12 +108,53 @@ public async Task ConnectAsync_Should_Connect_Successfully()
107108
[Fact]
108109
public async Task ConnectAsync_Throws_If_Already_Connected()
109110
{
110-
await using var transport = new SseClientTransport(_transportOptions, _serverConfig, NullLoggerFactory.Instance);
111-
transport.GetType().BaseType!.GetField("_isConnected", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance)?.SetValue(transport, true);
111+
using var mockHttpHandler = new MockHttpHandler();
112+
using var httpClient = new HttpClient(mockHttpHandler);
113+
await using var transport = new SseClientTransport(_transportOptions, _serverConfig, httpClient, NullLoggerFactory.Instance);
114+
using var mreConnected = new ManualResetEventSlim(false);
115+
using var mreDone = new ManualResetEventSlim(false);
116+
var callIndex = 0;
117+
118+
mockHttpHandler.RequestHandler = (request) =>
119+
{
120+
switch (callIndex++)
121+
{
122+
case 0:
123+
return Task.FromResult(new HttpResponseMessage
124+
{
125+
StatusCode = HttpStatusCode.OK,
126+
Content = new StringContent("event: endpoint\r\ndata: http://localhost\r\n\r\n")
127+
});
128+
case 1:
129+
mreConnected.Set();
130+
mreDone.Wait();
131+
return Task.FromResult(new HttpResponseMessage
132+
{
133+
StatusCode = HttpStatusCode.OK,
134+
Content = new StringContent("")
135+
});
136+
default:
137+
return Task.FromResult(new HttpResponseMessage
138+
{
139+
StatusCode = HttpStatusCode.OK,
140+
Content = new StringContent("")
141+
});
142+
}
143+
};
112144

145+
var task = Task.Run(async () =>
146+
{
147+
await transport.ConnectAsync(TestContext.Current.CancellationToken);
148+
}, TestContext.Current.CancellationToken);
149+
150+
mreConnected.Wait(TestContext.Current.CancellationToken);
151+
Assert.True(transport.IsConnected);
113152
var action = async () => await transport.ConnectAsync();
114153
var exception = await Assert.ThrowsAsync<McpTransportException>(action);
115154
Assert.Equal("Transport is already connected", exception.Message);
155+
mreDone.Set();
156+
await transport.CloseAsync();
157+
await task;
116158
}
117159

118160
[Fact]

0 commit comments

Comments
 (0)