Skip to content

Commit 12ba337

Browse files
CopilotCopilot
andcommitted
Replace Mock<McpServer> with real McpServer instances in McpServerToolTests
Replace all Moq-based Mock<McpServer> usages with real McpServer instances created via McpServer.Create() using TestServerTransport. This removes the dependency on Moq in this test file. Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
1 parent 802026b commit 12ba337

1 file changed

Lines changed: 60 additions & 58 deletions

File tree

tests/ModelContextProtocol.Tests/Server/McpServerToolTests.cs

Lines changed: 60 additions & 58 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
using Microsoft.Extensions.DependencyInjection;
44
using ModelContextProtocol.Protocol;
55
using ModelContextProtocol.Server;
6-
using Moq;
6+
using ModelContextProtocol.Tests.Utils;
77
using System.ComponentModel;
88
using System.Reflection;
99
using System.Runtime.InteropServices;
@@ -27,6 +27,9 @@ private static JsonRpcRequest CreateTestJsonRpcRequest()
2727
};
2828
}
2929

30+
private static McpServer CreateTestServer(IServiceProvider? services = null) =>
31+
McpServer.Create(new TestServerTransport(), new McpServerOptions(), serviceProvider: services);
32+
3033
public McpServerToolTests()
3134
{
3235
#if !NET
@@ -51,18 +54,18 @@ public void Create_InvalidArgs_Throws()
5154
[Fact]
5255
public async Task SupportsMcpServer()
5356
{
54-
Mock<McpServer> mockServer = new();
57+
McpServer server = CreateTestServer();
5558

56-
McpServerTool tool = McpServerTool.Create((McpServer server) =>
59+
McpServerTool tool = McpServerTool.Create((McpServer s) =>
5760
{
58-
Assert.Same(mockServer.Object, server);
61+
Assert.Same(server, s);
5962
return "42";
6063
});
6164

6265
Assert.DoesNotContain("server", JsonSerializer.Serialize(tool.ProtocolTool.InputSchema, McpJsonUtilities.DefaultOptions));
6366

6467
var result = await tool.InvokeAsync(
65-
new RequestContext<CallToolRequestParams>(mockServer.Object, CreateTestJsonRpcRequest()),
68+
new RequestContext<CallToolRequestParams>(server, CreateTestJsonRpcRequest()),
6669
TestContext.Current.CancellationToken);
6770
Assert.Equal("42", (result.Content[0] as TextContentBlock)?.Text);
6871
}
@@ -76,8 +79,7 @@ public async Task SupportsCtorInjection()
7679
sc.AddSingleton(expectedMyService);
7780
IServiceProvider services = sc.BuildServiceProvider();
7881

79-
Mock<McpServer> mockServer = new();
80-
mockServer.SetupGet(s => s.Services).Returns(services);
82+
McpServer server = CreateTestServer(services);
8183

8284
MethodInfo? testMethod = typeof(HasCtorWithSpecialParameters).GetMethod(nameof(HasCtorWithSpecialParameters.TestTool));
8385
Assert.NotNull(testMethod);
@@ -88,7 +90,7 @@ public async Task SupportsCtorInjection()
8890
}, new() { Services = services });
8991

9092
var result = await tool.InvokeAsync(
91-
new RequestContext<CallToolRequestParams>(mockServer.Object, CreateTestJsonRpcRequest()),
93+
new RequestContext<CallToolRequestParams>(server, CreateTestJsonRpcRequest()),
9294
TestContext.Current.CancellationToken);
9395
Assert.NotNull(result);
9496
Assert.NotNull(result.Content);
@@ -163,16 +165,16 @@ public async Task SupportsServiceFromDI(ServiceLifetime injectedArgumentLifetime
163165

164166
Assert.DoesNotContain("actualMyService", JsonSerializer.Serialize(tool.ProtocolTool.InputSchema, McpJsonUtilities.DefaultOptions));
165167

166-
Mock<McpServer> mockServer = new();
168+
McpServer server = CreateTestServer();
167169

168170
var ex = await Assert.ThrowsAsync<ArgumentException>(async () => await tool.InvokeAsync(
169-
new RequestContext<CallToolRequestParams>(mockServer.Object, CreateTestJsonRpcRequest()),
171+
new RequestContext<CallToolRequestParams>(server, CreateTestJsonRpcRequest()),
170172
TestContext.Current.CancellationToken));
171173

172-
mockServer.SetupGet(s => s.Services).Returns(services);
174+
McpServer serverWithServices = CreateTestServer(services);
173175

174176
var result = await tool.InvokeAsync(
175-
new RequestContext<CallToolRequestParams>(mockServer.Object, CreateTestJsonRpcRequest()) { Services = services },
177+
new RequestContext<CallToolRequestParams>(serverWithServices, CreateTestJsonRpcRequest()) { Services = services },
176178
TestContext.Current.CancellationToken);
177179
Assert.Equal("42", (result.Content[0] as TextContentBlock)?.Text);
178180
}
@@ -193,7 +195,7 @@ public async Task SupportsOptionalServiceFromDI()
193195
}, new() { Services = services });
194196

195197
var result = await tool.InvokeAsync(
196-
new RequestContext<CallToolRequestParams>(new Mock<McpServer>().Object, CreateTestJsonRpcRequest()),
198+
new RequestContext<CallToolRequestParams>(CreateTestServer(), CreateTestJsonRpcRequest()),
197199
TestContext.Current.CancellationToken);
198200
Assert.Equal("42", (result.Content[0] as TextContentBlock)?.Text);
199201
}
@@ -208,7 +210,7 @@ public async Task SupportsDisposingInstantiatedDisposableTargets()
208210
options);
209211

210212
var result = await tool1.InvokeAsync(
211-
new RequestContext<CallToolRequestParams>(new Mock<McpServer>().Object, CreateTestJsonRpcRequest()),
213+
new RequestContext<CallToolRequestParams>(CreateTestServer(), CreateTestJsonRpcRequest()),
212214
TestContext.Current.CancellationToken);
213215
Assert.Equal("""{"disposals":1}""", (result.Content[0] as TextContentBlock)?.Text);
214216
}
@@ -223,7 +225,7 @@ public async Task SupportsAsyncDisposingInstantiatedAsyncDisposableTargets()
223225
options);
224226

225227
var result = await tool1.InvokeAsync(
226-
new RequestContext<CallToolRequestParams>(new Mock<McpServer>().Object, CreateTestJsonRpcRequest()),
228+
new RequestContext<CallToolRequestParams>(CreateTestServer(), CreateTestJsonRpcRequest()),
227229
TestContext.Current.CancellationToken);
228230
Assert.Equal("""{"asyncDisposals":1}""", (result.Content[0] as TextContentBlock)?.Text);
229231
}
@@ -242,7 +244,7 @@ public async Task SupportsAsyncDisposingInstantiatedAsyncDisposableAndDisposable
242244
options);
243245

244246
var result = await tool1.InvokeAsync(
245-
new RequestContext<CallToolRequestParams>(new Mock<McpServer>().Object, CreateTestJsonRpcRequest()) { Services = services },
247+
new RequestContext<CallToolRequestParams>(CreateTestServer(), CreateTestJsonRpcRequest()) { Services = services },
246248
TestContext.Current.CancellationToken);
247249
Assert.Equal("""{"asyncDisposals":1,"disposals":0}""", (result.Content[0] as TextContentBlock)?.Text);
248250
}
@@ -251,10 +253,10 @@ public async Task SupportsAsyncDisposingInstantiatedAsyncDisposableAndDisposable
251253
[Fact]
252254
public async Task CanReturnCollectionOfAIContent()
253255
{
254-
Mock<McpServer> mockServer = new();
255-
McpServerTool tool = McpServerTool.Create((McpServer server) =>
256+
McpServer server = CreateTestServer();
257+
McpServerTool tool = McpServerTool.Create((McpServer s) =>
256258
{
257-
Assert.Same(mockServer.Object, server);
259+
Assert.Same(server, s);
258260
return new List<AIContent> {
259261
new TextContent("text"),
260262
new DataContent("data:image/png;base64,1234"),
@@ -263,7 +265,7 @@ public async Task CanReturnCollectionOfAIContent()
263265
}, new() { SerializerOptions = JsonContext2.Default.Options });
264266

265267
var result = await tool.InvokeAsync(
266-
new RequestContext<CallToolRequestParams>(mockServer.Object, CreateTestJsonRpcRequest()),
268+
new RequestContext<CallToolRequestParams>(server, CreateTestJsonRpcRequest()),
267269
TestContext.Current.CancellationToken);
268270

269271
Assert.Equal(3, result.Content.Count);
@@ -283,10 +285,10 @@ public async Task CanReturnCollectionOfAIContent()
283285
[InlineData("data:audio/wav;base64,1234", "audio")]
284286
public async Task CanReturnSingleAIContent(string data, string type)
285287
{
286-
Mock<McpServer> mockServer = new();
287-
McpServerTool tool = McpServerTool.Create((McpServer server) =>
288+
McpServer server = CreateTestServer();
289+
McpServerTool tool = McpServerTool.Create((McpServer s) =>
288290
{
289-
Assert.Same(mockServer.Object, server);
291+
Assert.Same(server, s);
290292
return type switch
291293
{
292294
"text" => (AIContent)new TextContent(data),
@@ -297,7 +299,7 @@ public async Task CanReturnSingleAIContent(string data, string type)
297299
});
298300

299301
var result = await tool.InvokeAsync(
300-
new RequestContext<CallToolRequestParams>(mockServer.Object, CreateTestJsonRpcRequest()),
302+
new RequestContext<CallToolRequestParams>(server, CreateTestJsonRpcRequest()),
301303
TestContext.Current.CancellationToken);
302304

303305
Assert.Single(result.Content);
@@ -326,29 +328,29 @@ public async Task CanReturnSingleAIContent(string data, string type)
326328
[Fact]
327329
public async Task CanReturnNullAIContent()
328330
{
329-
Mock<McpServer> mockServer = new();
330-
McpServerTool tool = McpServerTool.Create((McpServer server) =>
331+
McpServer server = CreateTestServer();
332+
McpServerTool tool = McpServerTool.Create((McpServer s) =>
331333
{
332-
Assert.Same(mockServer.Object, server);
334+
Assert.Same(server, s);
333335
return (string?)null;
334336
});
335337
var result = await tool.InvokeAsync(
336-
new RequestContext<CallToolRequestParams>(mockServer.Object, CreateTestJsonRpcRequest()),
338+
new RequestContext<CallToolRequestParams>(server, CreateTestJsonRpcRequest()),
337339
TestContext.Current.CancellationToken);
338340
Assert.Empty(result.Content);
339341
}
340342

341343
[Fact]
342344
public async Task CanReturnString()
343345
{
344-
Mock<McpServer> mockServer = new();
345-
McpServerTool tool = McpServerTool.Create((McpServer server) =>
346+
McpServer server = CreateTestServer();
347+
McpServerTool tool = McpServerTool.Create((McpServer s) =>
346348
{
347-
Assert.Same(mockServer.Object, server);
349+
Assert.Same(server, s);
348350
return "42";
349351
});
350352
var result = await tool.InvokeAsync(
351-
new RequestContext<CallToolRequestParams>(mockServer.Object, CreateTestJsonRpcRequest()),
353+
new RequestContext<CallToolRequestParams>(server, CreateTestJsonRpcRequest()),
352354
TestContext.Current.CancellationToken);
353355
Assert.Single(result.Content);
354356
Assert.Equal("42", Assert.IsType<TextContentBlock>(result.Content[0]).Text);
@@ -357,14 +359,14 @@ public async Task CanReturnString()
357359
[Fact]
358360
public async Task CanReturnCollectionOfStrings()
359361
{
360-
Mock<McpServer> mockServer = new();
361-
McpServerTool tool = McpServerTool.Create((McpServer server) =>
362+
McpServer server = CreateTestServer();
363+
McpServerTool tool = McpServerTool.Create((McpServer s) =>
362364
{
363-
Assert.Same(mockServer.Object, server);
365+
Assert.Same(server, s);
364366
return new List<string> { "42", "43" };
365367
}, new() { SerializerOptions = JsonContext2.Default.Options });
366368
var result = await tool.InvokeAsync(
367-
new RequestContext<CallToolRequestParams>(mockServer.Object, CreateTestJsonRpcRequest()),
369+
new RequestContext<CallToolRequestParams>(server, CreateTestJsonRpcRequest()),
368370
TestContext.Current.CancellationToken);
369371
Assert.Single(result.Content);
370372
Assert.Equal("""["42","43"]""", Assert.IsType<TextContentBlock>(result.Content[0]).Text);
@@ -373,14 +375,14 @@ public async Task CanReturnCollectionOfStrings()
373375
[Fact]
374376
public async Task CanReturnMcpContent()
375377
{
376-
Mock<McpServer> mockServer = new();
377-
McpServerTool tool = McpServerTool.Create((McpServer server) =>
378+
McpServer server = CreateTestServer();
379+
McpServerTool tool = McpServerTool.Create((McpServer s) =>
378380
{
379-
Assert.Same(mockServer.Object, server);
381+
Assert.Same(server, s);
380382
return new TextContentBlock { Text = "42" };
381383
});
382384
var result = await tool.InvokeAsync(
383-
new RequestContext<CallToolRequestParams>(mockServer.Object, CreateTestJsonRpcRequest()),
385+
new RequestContext<CallToolRequestParams>(server, CreateTestJsonRpcRequest()),
384386
TestContext.Current.CancellationToken);
385387
Assert.Single(result.Content);
386388
Assert.Equal("42", Assert.IsType<TextContentBlock>(result.Content[0]).Text);
@@ -390,18 +392,18 @@ public async Task CanReturnMcpContent()
390392
[Fact]
391393
public async Task CanReturnCollectionOfMcpContent()
392394
{
393-
Mock<McpServer> mockServer = new();
394-
McpServerTool tool = McpServerTool.Create((McpServer server) =>
395+
McpServer server = CreateTestServer();
396+
McpServerTool tool = McpServerTool.Create((McpServer s) =>
395397
{
396-
Assert.Same(mockServer.Object, server);
398+
Assert.Same(server, s);
397399
return (IList<ContentBlock>)
398400
[
399401
new TextContentBlock { Text = "42" },
400402
ImageContentBlock.FromBytes((byte[])[1, 2, 3, 4], "image/png")
401403
];
402404
});
403405
var result = await tool.InvokeAsync(
404-
new RequestContext<CallToolRequestParams>(mockServer.Object, CreateTestJsonRpcRequest()),
406+
new RequestContext<CallToolRequestParams>(server, CreateTestJsonRpcRequest()),
405407
TestContext.Current.CancellationToken);
406408
Assert.Equal(2, result.Content.Count);
407409
Assert.Equal("42", Assert.IsType<TextContentBlock>(result.Content[0]).Text);
@@ -417,14 +419,14 @@ public async Task CanReturnCallToolResult()
417419
Content = [new TextContentBlock { Text = "text" }, ImageContentBlock.FromBytes((byte[])[1, 2, 3, 4], "image/png")]
418420
};
419421

420-
Mock<McpServer> mockServer = new();
421-
McpServerTool tool = McpServerTool.Create((McpServer server) =>
422+
McpServer server = CreateTestServer();
423+
McpServerTool tool = McpServerTool.Create((McpServer s) =>
422424
{
423-
Assert.Same(mockServer.Object, server);
425+
Assert.Same(server, s);
424426
return response;
425427
});
426428
var result = await tool.InvokeAsync(
427-
new RequestContext<CallToolRequestParams>(mockServer.Object, CreateTestJsonRpcRequest()),
429+
new RequestContext<CallToolRequestParams>(server, CreateTestJsonRpcRequest()),
428430
TestContext.Current.CancellationToken);
429431

430432
Assert.Same(response, result);
@@ -463,8 +465,8 @@ public async Task StructuredOutput_Enabled_ReturnsExpectedSchema<T>(T value)
463465
{
464466
JsonSerializerOptions options = new() { TypeInfoResolver = new DefaultJsonTypeInfoResolver() };
465467
McpServerTool tool = McpServerTool.Create(() => value, new() { Name = "tool", UseStructuredContent = true, SerializerOptions = options });
466-
var mockServer = new Mock<McpServer>();
467-
var request = new RequestContext<CallToolRequestParams>(mockServer.Object, CreateTestJsonRpcRequest())
468+
McpServer server = CreateTestServer();
469+
var request = new RequestContext<CallToolRequestParams>(server, CreateTestJsonRpcRequest())
468470
{
469471
Params = new CallToolRequestParams { Name = "tool" },
470472
};
@@ -481,8 +483,8 @@ public async Task StructuredOutput_Enabled_ReturnsExpectedSchema<T>(T value)
481483
public async Task StructuredOutput_Enabled_VoidReturningTools_ReturnsExpectedSchema()
482484
{
483485
McpServerTool tool = McpServerTool.Create(() => { });
484-
var mockServer = new Mock<McpServer>();
485-
var request = new RequestContext<CallToolRequestParams>(mockServer.Object, CreateTestJsonRpcRequest())
486+
McpServer server = CreateTestServer();
487+
var request = new RequestContext<CallToolRequestParams>(server, CreateTestJsonRpcRequest())
486488
{
487489
Params = new CallToolRequestParams { Name = "tool" },
488490
};
@@ -493,7 +495,7 @@ public async Task StructuredOutput_Enabled_VoidReturningTools_ReturnsExpectedSch
493495
Assert.Null(result.StructuredContent);
494496

495497
tool = McpServerTool.Create(() => Task.CompletedTask);
496-
request = new RequestContext<CallToolRequestParams>(mockServer.Object, CreateTestJsonRpcRequest())
498+
request = new RequestContext<CallToolRequestParams>(server, CreateTestJsonRpcRequest())
497499
{
498500
Params = new CallToolRequestParams { Name = "tool" },
499501
};
@@ -504,7 +506,7 @@ public async Task StructuredOutput_Enabled_VoidReturningTools_ReturnsExpectedSch
504506
Assert.Null(result.StructuredContent);
505507

506508
tool = McpServerTool.Create(() => default(ValueTask));
507-
request = new RequestContext<CallToolRequestParams>(mockServer.Object, CreateTestJsonRpcRequest())
509+
request = new RequestContext<CallToolRequestParams>(server, CreateTestJsonRpcRequest())
508510
{
509511
Params = new CallToolRequestParams { Name = "tool" },
510512
};
@@ -521,8 +523,8 @@ public async Task StructuredOutput_Disabled_ReturnsExpectedSchema<T>(T value)
521523
{
522524
JsonSerializerOptions options = new() { TypeInfoResolver = new DefaultJsonTypeInfoResolver() };
523525
McpServerTool tool = McpServerTool.Create(() => value, new() { UseStructuredContent = false, SerializerOptions = options });
524-
var mockServer = new Mock<McpServer>();
525-
var request = new RequestContext<CallToolRequestParams>(mockServer.Object, CreateTestJsonRpcRequest())
526+
McpServer server = CreateTestServer();
527+
var request = new RequestContext<CallToolRequestParams>(server, CreateTestJsonRpcRequest())
526528
{
527529
Params = new CallToolRequestParams { Name = "tool" },
528530
};
@@ -819,11 +821,11 @@ public void ReturnDescription_StructuredOutputEnabled_WithExplicitDescription_No
819821
public async Task EnablePollingAsync_ThrowsInvalidOperationException_WhenTransportIsNotStreamableHttpPost()
820822
{
821823
// Arrange
822-
Mock<McpServer> mockServer = new();
824+
McpServer server = CreateTestServer();
823825
var jsonRpcRequest = CreateTestJsonRpcRequest();
824826

825827
// The JsonRpcRequest has no Context, so RelatedTransport will be null
826-
var requestContext = new RequestContext<CallToolRequestParams>(mockServer.Object, jsonRpcRequest);
828+
var requestContext = new RequestContext<CallToolRequestParams>(server, jsonRpcRequest);
827829

828830
// Act & Assert
829831
var exception = await Assert.ThrowsAsync<InvalidOperationException>(

0 commit comments

Comments
 (0)