home / skills / stuartf303 / sorcha / moq

moq skill

/.claude/skills/moq

This skill helps you mock dependencies with Moq to isolate units, verify interactions, and accelerate reliable .NET testing.

npx playbooks add skill stuartf303/sorcha --skill moq

Review the files below or copy the command above to add this skill to your agents.

Files (3)
SKILL.md
3.2 KB
---
name: moq
description: |
  Mocks dependencies in unit tests using Moq framework.
  Use when: writing unit tests, creating test doubles for interfaces, verifying method calls, mocking async operations
allowed-tools: Read, Edit, Write, Glob, Grep, Bash, mcp__context7__resolve-library-id, mcp__context7__query-docs
---

# Moq Skill

Moq provides type-safe mocking for .NET unit tests. Sorcha uses Moq extensively across 30+ test projects to isolate components and verify interactions. The codebase favors constructor injection with mocks stored as `private readonly` fields.

## Quick Start

### Basic Mock Setup

```csharp
public class WalletManagerTests
{
    private readonly Mock<ICryptoModule> _mockCryptoModule;
    private readonly Mock<IHashProvider> _mockHashProvider;

    public WalletManagerTests()
    {
        _mockCryptoModule = new Mock<ICryptoModule>();
        _mockHashProvider = new Mock<IHashProvider>();
    }
}
```

### Async Method Mock

```csharp
_mockCryptoModule
    .Setup(x => x.GenerateKeySetAsync(
        It.IsAny<WalletNetworks>(),
        It.IsAny<byte[]>(),
        It.IsAny<CancellationToken>()))
    .ReturnsAsync(CryptoResult<KeySet>.Success(keySet));
```

### Verification

```csharp
_mockRegisterManager.Verify(
    m => m.CreateRegisterAsync("Test Register", "tenant-123", false, true, It.IsAny<CancellationToken>()),
    Times.Once);
```

## Key Concepts

| Concept | Usage | Example |
|---------|-------|---------|
| `Mock<T>` | Create mock instance | `new Mock<IService>()` |
| `.Object` | Get mock instance | `_mock.Object` |
| `Mock.Of<T>()` | Quick mock for simple deps | `Mock.Of<ILogger<T>>()` |
| `Setup()` | Configure behavior | `.Setup(x => x.Method())` |
| `ReturnsAsync()` | Async return value | `.ReturnsAsync(result)` |
| `Callback()` | Capture arguments | `.Callback<T>((arg) => captured = arg)` |
| `Verify()` | Assert method called | `.Verify(x => x.Method(), Times.Once)` |
| `It.IsAny<T>()` | Match any argument | `It.IsAny<string>()` |
| `It.Is<T>()` | Match with predicate | `It.Is<T>(x => x.Id == 1)` |

## Common Patterns

### Logger Mock (Quick)

**When:** You need a logger but don't care about verifying logs.

```csharp
var service = new WalletManager(Mock.Of<ILogger<WalletManager>>());
```

### Options Pattern Mock

**When:** Injecting `IOptions<T>` dependencies.

```csharp
var mockConfig = new Mock<IOptions<PeerServiceConfiguration>>();
mockConfig.Setup(x => x.Value).Returns(new PeerServiceConfiguration { Enabled = true });
```

## See Also

- [patterns](references/patterns.md) - Detailed setup and verification patterns
- [workflows](references/workflows.md) - Test writing workflows and integration testing

## Related Skills

- See the **xunit** skill for test framework patterns
- See the **fluent-assertions** skill for assertion syntax
- See the **entity-framework** skill for mocking DbContext

## Documentation Resources

> Fetch latest Moq documentation with Context7.

**How to use Context7:**
1. Use `mcp__context7__resolve-library-id` to search for "moq"
2. Query with `mcp__context7__query-docs` using the resolved library ID

**Library ID:** `/devlooped/moq`

**Recommended Queries:**
- "moq setup verify async methods"
- "moq callbacks parameter capture"
- "moq argument matching It.Is"

Overview

This skill provides practical patterns for mocking dependencies in C# unit tests using the Moq framework. It covers setup for synchronous and asynchronous calls, verification of interactions, and common helper patterns used across many test projects. The guidance focuses on creating type-safe test doubles, capturing arguments, and keeping tests isolated and readable.

How this skill works

The skill shows how to create Mock<T> instances, access the mocked object via .Object, and configure behavior with Setup and Returns/ReturnsAsync. It demonstrates argument matching with It.Is/It.IsAny, capturing inputs with Callback, and asserting calls with Verify and Times. Common DI patterns are handled, including constructor-injected mocks and mocking IOptions and ILogger dependencies.

When to use it

  • Writing unit tests that require replacing interfaces or external services
  • Creating test doubles for interfaces to isolate units under test
  • Verifying that methods were invoked with expected arguments and call counts
  • Mocking asynchronous methods that return Task/Task<T>
  • Quickly injecting simple dependencies like ILogger or IOptions

Best practices

  • Favor constructor injection and store mocks as private readonly fields for reuse and clarity
  • Use ReturnsAsync for async methods and avoid blocking on Tasks in tests
  • Prefer specific It.Is predicates for meaningful argument checks over broad It.IsAny when possible
  • Use Callback to capture parameters you want to assert on later instead of complex setups
  • Keep mock setups focused on behavior needed for the test; avoid over-configuring unrelated methods
  • Verify interactions when side effects are part of the behavior; assert returned results for pure functions

Example use cases

  • Mock an ICryptoModule.GenerateKeySetAsync to return a successful KeySet for positive flow tests
  • Verify a RegisterManager.CreateRegisterAsync was called exactly once with expected parameters
  • Inject Mock.Of<ILogger<T>> when logging is required but not asserted
  • Mock IOptions<T>.Value to supply configuration settings to services under test
  • Capture an argument passed to a dependency using Callback and assert on its properties afterwards

FAQ

How do I mock an async method to return a value?

Use Setup(...).ReturnsAsync(value) on the mock for methods that return Task<T>. For Task methods use Returns(Task.CompletedTask) or ReturnsAsync when returning a value.

When should I use Mock.Of<T>() vs new Mock<T>()?

Use Mock.Of<T>() for quick, read-only mocks where behavior doesn’t need verification. Use new Mock<T>() when you need Setup, Callback, or Verify.