Course contentsShow
← Software Engineering
Lesson 475 of 1,93314. Test DoublesFree lesson

Mocking at the Boundary

Understand why mocking external dependencies at system boundaries produces more maintainable tests than deep mocking.

Mocking at the Boundary

You'll learn why mocking external dependencies at system boundaries leads to more maintainable tests than mocking deep inside your code.

The Core Idea

When you use mocks (test doubles that verify interactions), place them at the edges of your system—where your code talks to the outside world—rather than deep within your own business logic.

Think of your application like a house. The boundaries are the doors and windows—places where you interact with the outside (databases, APIs, file systems, third-party services). Mocking at the boundary means putting your test doubles at these entry/exit points, not in the middle of your living room.

Why This Matters

Deep mocking couples your tests to internal implementation details. If you mock several layers down in your code, every refactoring of your internal structure breaks tests—even when external behavior hasn't changed.

Boundary mocking keeps tests focused on outcomes. Your tests mock the database adapter or HTTP client, but let your business logic run naturally. This means:

  • You can refactor internal code without breaking tests
  • Tests verify real behavior paths through your logic
  • You catch integration issues between your own classes
  • Tests stay simple—fewer mocks to set up and verify

Example Thinking

Instead of mocking UserValidator, UserRepository, and EmailFormatter inside your UserRegistration class, mock only the Database and EmailService at your system's boundary. Let UserRegistration and its helpers run for real.

Key Takeaway: Mock at your system's boundaries (external services, I/O) rather than between your own classes—this produces tests that survive refactoring and verify meaningful behavior.