Moq

Mocking library for .NET — creates test doubles (mocks) of interfaces and abstract classes using lambda-based LINQ setup API. Moq features: var mock = new Mock<IAgentRepository>(); mock.Setup(r => r.FindAsync(agentId)).ReturnsAsync(agent) stubs method return; mock.Verify(r => r.SaveAsync(It.IsAny<Agent>()), Times.Once()) verifies call occurred; Mock.Of<T>() for inline mock creation; MockBehavior.Strict throws on unexpected calls; Callback for capturing arguments; SetupSequence for multiple sequential returns. Moq uses Castle.DynamicProxy to generate mock implementations at runtime. Most widely used .NET mocking library. Works with xUnit, NUnit, and MSTest for agent service unit tests.

Evaluated Mar 06, 2026 (0d ago) v4.x
Homepage ↗ Repo ↗ Developer Tools dotnet csharp mocking unit-testing test-double mock stub verify
&#9881; Agent Friendliness
69
/ 100
Can an agent use this?
&#128274; Security
92
/ 100
Is it safe for agents?
&#9889; Reliability
88
/ 100
Does it work consistently?

Score Breakdown

⚙ Agent Friendliness

MCP Quality
--
Documentation
88
Error Messages
88
Auth Simplicity
98
Rate Limits
98

🔒 Security

TLS Enforcement
95
Auth Strength
95
Scope Granularity
90
Dep. Hygiene
85
Secret Handling
95

Mocking library for tests only — never use in production code. Ensures agent service unit tests don't make real external calls (LLM APIs, databases) preventing credential leakage in CI. Note: use v4.20+ to avoid deprecated SponsorLink telemetry from earlier versions.

⚡ Reliability

Uptime/SLA
92
Version Stability
88
Breaking Changes
82
Error Recovery
90
AF Security Reliability

Best When

You're writing .NET agent service unit tests that need to isolate dependencies (repositories, external APIs, LLM clients) — Moq's lambda setup API is the most intuitive mocking experience for C# developers.

Avoid When

You need to mock static/sealed classes (use Fakes or refactor), you prefer source-generator-based mocking (use Moq.AutoMock or Rocks), or you want F# native testing.

Use Cases

  • Mock agent repository in handler tests — var repoMock = new Mock<IAgentRepository>(); repoMock.Setup(r => r.GetByIdAsync(agentId, ct)).ReturnsAsync(testAgent); inject mock into CreateAgentCommandHandler; verify handler calls repo correctly
  • Verify agent service method calls — mock.Verify(s => s.SendNotification(It.Is<string>(id => id == agentId), It.IsAny<string>()), Times.Once()) asserts agent service sent exactly one notification with correct agent ID
  • Stub LLM client for agent tests — var llmMock = new Mock<ILlmClient>(); llmMock.Setup(c => c.CompleteAsync(It.IsAny<string>(), ct)).ReturnsAsync("Agent response") stubs LLM without API calls in agent unit tests
  • Callback to capture agent arguments — mock.Setup(r => r.SaveAsync(It.IsAny<Agent>(), ct)).Callback<Agent, CancellationToken>((a, _) => savedAgent = a).ReturnsAsync(true) captures saved agent for assertions
  • Setup sequences for agent state machine tests — mock.SetupSequence(r => r.GetStatusAsync(id)).ReturnsAsync(Status.Pending).ReturnsAsync(Status.Running).ReturnsAsync(Status.Complete) simulates agent status progression

Not For

  • Mocking static methods or sealed classes — Moq cannot mock static methods, sealed classes without interfaces, or extension methods; for agent code with static dependencies, refactor to use interfaces or use Fakes (MSTest) for system statics
  • Integration tests — Moq is for unit test isolation; integration tests should use real implementations or test databases for agent service behavior verification
  • Performance-critical test suites — Moq uses reflection and Castle.DynamicProxy; large test suites with thousands of mocks are slower than NSubstitute; benchmark if agent test execution time is critical

Interface

REST API
No
GraphQL
No
gRPC
No
MCP Server
No
SDK
Yes
Webhooks
No

Authentication

Methods: none
OAuth: No Scopes: No

Mocking library — no auth concepts.

Pricing

Model: open_source
Free tier: Yes
Requires CC: No

Moq is BSD-3 licensed. Free for all use. Note: 2023 controversy over SponsorLink telemetry was resolved; v4.20+ removed SponsorLink.

Agent Metadata

Pagination
none
Idempotent
Full
Retry Guidance
Not documented

Known Gotchas

  • Only interfaces and virtual methods can be mocked — new Mock<AgentService>() fails if AgentService is sealed or has non-virtual methods; Moq can only intercept virtual/abstract members; refactor agent service to use interface (IAgentService) and mock the interface for unit testing
  • Setup must match exact arguments or use It.IsAny — mock.Setup(r => r.GetAsync(agentId)) only matches exact agentId value; if test calls GetAsync with different ID, setup doesn't match and returns default null; use It.IsAny<string>() for flexible matching or It.Is<string>(id => id.StartsWith('agent-')) for agent ID pattern matching
  • Verify after act, not before — mock.Verify() checks if method was called during test; calling Verify before the actual code-under-test runs always fails; structure agent tests as Arrange (setup mock) → Act (call handler) → Assert (verify mock calls); common mistake is verifying in Arrange phase
  • MockBehavior.Strict throws on any unsetup call — strict mocks throw MockException for any method call without matching Setup; for agent tests, strict behavior prevents accidental calls to real dependencies but requires setting up all methods called by agent code under test; loose (default) returns defaults without setup
  • Returns vs ReturnsAsync for async methods — mock.Setup(r => r.GetAsync(id)).Returns(Task.FromResult(agent)) works but mock.Setup(r => r.GetAsync(id)).ReturnsAsync(agent) is cleaner; Returns(null) for async methods returns null Task causing NullReferenceException; always use ReturnsAsync for agent async interface mocks
  • Captured callbacks execute during Act not Arrange — .Callback(x => captured = x) runs when mocked method is called; captured value not available during setup phase; assert captured value in Assert phase after agent code calls the mock; using captured before Act causes null/default value assertion failure

Alternatives

Full Evaluation Report

Detailed scoring breakdown, competitive positioning, security analysis, and improvement recommendations for Moq.

$99

Scores are editorial opinions as of 2026-03-06.

5215
Packages Evaluated
26151
Need Evaluation
173
Need Re-evaluation
Community Powered