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

Mock Frameworks and Hand-Rolled Doubles

Evaluate trade-offs between using mocking libraries and writing custom test doubles for different testing scenarios.

Mock Frameworks and Hand-Rolled Doubles

You'll learn: When to use a mocking library versus writing your own test doubles manually.

The Choice: Library or DIY?

You've learned about dummies, stubs, fakes, spies, and mocks—the different types of test doubles. Now comes a practical decision: should you use a mocking framework (like a power tool) or write your own test doubles by hand (like using manual tools)?

Mock Frameworks: The Power Tool

Mocking libraries let you create test doubles on-the-fly with minimal code. They shine when you need:

  • Complex interaction verification – tracking call counts, argument matching, call order
  • Quick setup – creating doubles for interfaces with many methods
  • Flexibility – different behavior per test without creating multiple classes

The trade-off? They add a dependency, have a learning curve, and can make tests harder to read if overused.

Hand-Rolled Doubles: The Manual Approach

Writing your own test double means creating a simple class yourself. This works best when:

  • The interface is small – stubbing 2-3 methods is straightforward
  • Behavior is reused – the same fake database is useful across many tests
  • Readability matters – a class named AlwaysSuccessfulPaymentGateway is clearer than mock configuration
  • You want explicit control – no "magic" or framework surprises

The trade-off? More code to maintain and less flexibility for one-off scenarios.

Guidelines for Choosing

Use a mock framework for complex verification or when you need many different behaviors across tests. Use hand-rolled doubles when the double is simple, reused, or when clarity trumps brevity.

Many teams use both: hand-rolled fakes for common scenarios (like an in-memory database) and mocking frameworks for interaction verification or one-off stubs.

Key Takeaway: Mock frameworks offer power and speed; hand-rolled doubles offer simplicity and clarity—choose based on test complexity, reusability, and team familiarity.