Skip to content

Commit d18da9a

Browse files
Remove reflection from Connect test (#57)
* 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 * remove unneeded using --------- Co-authored-by: Stephen Toub <[email protected]>
1 parent 08e7da1 commit d18da9a

File tree

1 file changed

+43
-2
lines changed

1 file changed

+43
-2
lines changed

tests/ModelContextProtocol.Tests/Transport/SseClientTransportTests.cs

+43-2
Original file line numberDiff line numberDiff line change
@@ -107,12 +107,53 @@ public async Task ConnectAsync_Should_Connect_Successfully()
107107
[Fact]
108108
public async Task ConnectAsync_Throws_If_Already_Connected()
109109
{
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);
110+
using var mockHttpHandler = new MockHttpHandler();
111+
using var httpClient = new HttpClient(mockHttpHandler);
112+
await using var transport = new SseClientTransport(_transportOptions, _serverConfig, httpClient, NullLoggerFactory.Instance);
113+
using var mreConnected = new ManualResetEventSlim(false);
114+
using var mreDone = new ManualResetEventSlim(false);
115+
var callIndex = 0;
116+
117+
mockHttpHandler.RequestHandler = (request) =>
118+
{
119+
switch (callIndex++)
120+
{
121+
case 0:
122+
return Task.FromResult(new HttpResponseMessage
123+
{
124+
StatusCode = HttpStatusCode.OK,
125+
Content = new StringContent("event: endpoint\r\ndata: http://localhost\r\n\r\n")
126+
});
127+
case 1:
128+
mreConnected.Set();
129+
mreDone.Wait();
130+
return Task.FromResult(new HttpResponseMessage
131+
{
132+
StatusCode = HttpStatusCode.OK,
133+
Content = new StringContent("")
134+
});
135+
default:
136+
return Task.FromResult(new HttpResponseMessage
137+
{
138+
StatusCode = HttpStatusCode.OK,
139+
Content = new StringContent("")
140+
});
141+
}
142+
};
112143

144+
var task = Task.Run(async () =>
145+
{
146+
await transport.ConnectAsync(TestContext.Current.CancellationToken);
147+
}, TestContext.Current.CancellationToken);
148+
149+
mreConnected.Wait(TestContext.Current.CancellationToken);
150+
Assert.True(transport.IsConnected);
113151
var action = async () => await transport.ConnectAsync();
114152
var exception = await Assert.ThrowsAsync<McpTransportException>(action);
115153
Assert.Equal("Transport is already connected", exception.Message);
154+
mreDone.Set();
155+
await transport.CloseAsync();
156+
await task;
116157
}
117158

118159
[Fact]

0 commit comments

Comments
 (0)