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

Testing Through Interfaces

Design code with dependency injection and interfaces to make test doubles natural without tight coupling to mocking tools.

Testing Through Interfaces

You'll learn how designing code around interfaces and dependency injection makes test doubles feel natural and keeps your tests decoupled from specific mocking tools.

The Core Idea

When you write code that depends on interfaces (contracts) rather than concrete classes, you create natural seams for testing. By injecting dependencies through constructors or parameters, you can easily swap real implementations for test doubles—without forcing your production code to know anything about mocking frameworks.

This approach means your test doubles become just another implementation of the interface, rather than magical mock objects that your code must somehow accommodate.

Why This Matters

If you design a class that directly creates its own dependencies (like new EmailService() inside the class), you're stuck testing with the real EmailService. But if your class accepts an IEmailService interface through its constructor, you can pass in a stub or fake during testing.

The beauty: your production code never mentions test doubles. It just expects something that honors the interface contract. Your tests supply doubles; your app supplies real implementations.

The Pattern in Practice

Production code:

class OrderProcessor {
  constructor(emailService) {
    this.emailService = emailService; // accepts any object with send()
  }
  
  process(order) {
    // ... process order
    this.emailService.send(order.email, "Order confirmed");
  }
}

Test code:

const stubEmail = {
  send: () => {} // simple stub, no mocking framework needed
};
const processor = new OrderProcessor(stubEmail);

This is dependency injection at its simplest: pass in what you need, accept interfaces, stay flexible.

Key Takeaway: Design your code to depend on interfaces and inject dependencies from outside—this makes test doubles drop in naturally without coupling your codebase to any specific mocking tool.