Mocking and stubbing are essential techniques for isolating units of code during testing by replacing dependencies with controlled test doubles. This enables fast, reliable, and focused unit tests that don't depend on external systems like databases, APIs, or file systems.
When to Use
Isolating unit tests from external dependencies
Testing code that depends on slow operations (DB, network)
Simulating error conditions and edge cases
Verifying interactions between objects
Testing code with non-deterministic behavior (time, randomness)
Avoiding expensive operations in tests
Testing error handling without triggering real failures
Quick Start
Minimal working example:
// services/UserService.ts
import { UserRepository } from "./UserRepository";
import { EmailService } from "./EmailService";
export class UserService {
constructor(
private userRepository: UserRepository,
private emailService: EmailService,
) {}
async createUser(userData: CreateUserDto) {
const user = await this.userRepository.create(userData);
await this.emailService.sendWelcomeEmail(user.email, user.name);
return user;
}
async getUserStats(userId: string) {
const user = await this.userRepository.findById(userId);
if (!user) throw new Error("User not found");
const orderCount = await this.userRepository.getOrderCount(userId);
return { ...user, orderCount };
}
}
// ... (see reference guides for full implementation)
Reference Guides
Detailed implementations in the references/ directory:
Guide
Contents
Jest Mocking (JavaScript/TypeScript)
Jest Mocking (JavaScript/TypeScript)
Python Mocking with unittest.mock
Python Mocking with unittest.mock
Mockito for Java
Mockito for Java
Advanced Mocking Patterns
Advanced Mocking Patterns
Best Practices
✅ DO
Mock external dependencies (DB, API, file system)
Use dependency injection for easier mocking
Verify important interactions with mocks
Reset mocks between tests
Mock at the boundary (repositories, services)
Use spies for partial mocking when needed
Create reusable mock factories
Test both success and failure scenarios
❌ DON'T
Mock everything (don't mock what you own)
Over-specify mock interactions
Use mocks in integration tests
Mock simple utility functions
Create complex mock hierarchies
Forget to verify mock calls
Share mocks between tests
Mock just to make tests pass
Converted and distributed by TomeVault — claim your Tome and manage your conversions.
1---2name: aj-geddes-useful-ai-prompts-mocking-stubbing3description: Mocking and Stubbing4---56# Mocking and Stubbing78## Table of Contents910- [Overview](#overview)11- [When to Use](#when-to-use)12- [Quick Start](#quick-start)13- [Reference Guides](#reference-guides)14- [Best Practices](#best-practices)1516## Overview1718Mocking and stubbing are essential techniques for isolating units of code during testing by replacing dependencies with controlled test doubles. This enables fast, reliable, and focused unit tests that don't depend on external systems like databases, APIs, or file systems.1920## When to Use2122- Isolating unit tests from external dependencies23- Testing code that depends on slow operations (DB, network)24- Simulating error conditions and edge cases25- Verifying interactions between objects26- Testing code with non-deterministic behavior (time, randomness)27- Avoiding expensive operations in tests28- Testing error handling without triggering real failures2930## Quick Start3132Minimal working example:3334```typescript35// services/UserService.ts36import { UserRepository } from "./UserRepository";37import { EmailService } from "./EmailService";3839export class UserService {40 constructor(41 private userRepository: UserRepository,42 private emailService: EmailService,43 ) {}4445 async createUser(userData: CreateUserDto) {46 const user = await this.userRepository.create(userData);47 await this.emailService.sendWelcomeEmail(user.email, user.name);48 return user;49 }5051 async getUserStats(userId: string) {52 const user = await this.userRepository.findById(userId);53 if (!user) throw new Error("User not found");5455 const orderCount = await this.userRepository.getOrderCount(userId);56 return { ...user, orderCount };57 }58}5960// ... (see reference guides for full implementation)61```6263## Reference Guides6465Detailed implementations in the `references/` directory:6667| Guide | Contents |68|---|---|69| [Jest Mocking (JavaScript/TypeScript)](references/jest-mocking-javascripttypescript.md) | Jest Mocking (JavaScript/TypeScript) |70| [Python Mocking with unittest.mock](references/python-mocking-with-unittestmock.md) | Python Mocking with unittest.mock |71| [Mockito for Java](references/mockito-for-java.md) | Mockito for Java |72| [Advanced Mocking Patterns](references/advanced-mocking-patterns.md) | Advanced Mocking Patterns |7374## Best Practices7576### ✅ DO7778- Mock external dependencies (DB, API, file system)79- Use dependency injection for easier mocking80- Verify important interactions with mocks81- Reset mocks between tests82- Mock at the boundary (repositories, services)83- Use spies for partial mocking when needed84- Create reusable mock factories85- Test both success and failure scenarios8687### ❌ DON'T8889- Mock everything (don't mock what you own)90- Over-specify mock interactions91- Use mocks in integration tests92- Mock simple utility functions93- Create complex mock hierarchies94- Forget to verify mock calls95- Share mocks between tests96- Mock just to make tests pass9798---99> Converted and distributed by [TomeVault](https://tomevault.io/claim/aj-geddes) — claim your Tome and manage your conversions.100<!-- tomevault:4.0:skill_md:2026-04-11 -->
Run npx skillmds@latest add tomevault-io/aj-geddes-useful-ai-prompts-mocking-stubbing in your terminal (requires Node.js), paste this page's agent-chat prompt into Claude, Cursor, or any MCP-connected agent, or download the SKILL.md file and copy it into your agent's skills directory.
Mocking and Stubbing It is listed under Coding & Dev Tools on SkillMD.
This skill has not completed SkillMD's automated safety review yet. Independent scanners report: SkillSpector: PASS, Skill Scanner: PASS. SkillMD never runs a skill's scripts for you; review the SKILL.md before installing.
This skill is tagged as working with Claude Code, Claude.ai, OpenAI Codex. SKILL.md is an open format, so most agents that read a skills directory can load it too.
Yes. Installing skills from SkillMD is free, and the skill stays under its author's original license.
tomevault-io (@tomevault-io) published this skill. Their other Agent Skills are listed on their SkillMD profile.