Test Doubles and Dependency Injection: Making Code Testable
Test doubles — mocks, stubs, fakes, spies — only work if you can inject them. Code that creates its own dependencies is untestable by definition. Dependency injection (DI) is the prerequisite.
This guide covers the connection between DI and test doubles, the DI patterns that work best for testing, and language-specific examples.
Why You Can't Test Without DI
# Untestable: UserService creates its own database connection
class UserService:
def __init__(self):
self.db = PostgresConnection(
host=os.environ['DB_HOST'],
password=os.environ['DB_PASSWORD']
)
def get_user(self, user_id):
return self.db.query_one("SELECT * FROM users WHERE id = ?", [user_id])To test get_user, you'd need a real PostgreSQL database. You can't substitute a fake or stub because UserService controls what self.db is.
# Testable: database is injected
class UserService:
def __init__(self, db):
self.db = db
def get_user(self, user_id):
return self.db.query_one("SELECT * FROM users WHERE id = ?", [user_id])
# In tests:
def test_get_user_returns_none_on_miss(mocker):
db_stub = mocker.MagicMock()
db_stub.query_one.return_value = None
service = UserService(db=db_stub)
assert service.get_user('nonexistent') is NoneOne change — inject instead of create — unlocks all test double patterns.
DI Patterns for Testability
Constructor Injection (Most Common)
Pass dependencies through the constructor. This is the default choice for most code.
public class PaymentProcessor {
private final PaymentGateway gateway;
private final AuditLogger logger;
public PaymentProcessor(PaymentGateway gateway, AuditLogger logger) {
this.gateway = gateway;
this.logger = logger;
}
public PaymentResult process(Payment payment) {
PaymentResult result = gateway.charge(payment);
logger.log(payment.getId(), result.getStatus());
return result;
}
}Test:
@Test
void logsFailedPayments() {
PaymentGateway failingGateway = mock(PaymentGateway.class);
when(failingGateway.charge(any())).thenReturn(PaymentResult.failed("insufficient_funds"));
AuditLogger mockLogger = mock(AuditLogger.class);
PaymentProcessor processor = new PaymentProcessor(failingGateway, mockLogger);
processor.process(testPayment());
verify(mockLogger).log(anyString(), eq("failed"));
}Method Injection
Pass dependencies as method arguments. Use this when the dependency varies per-call, not per-instance.
// Production code
async function fetchAndProcess(
userId: string,
fetcher: UserFetcher = defaultFetcher
): Promise<ProcessedUser> {
const user = await fetcher.getUser(userId);
return processUser(user);
}
// Test: inject a stub for the fetcher
test('processesUserCorrectly', async () => {
const stubFetcher: UserFetcher = {
getUser: jest.fn().mockResolvedValue({ id: '1', name: 'Alice', active: true })
};
const result = await fetchAndProcess('1', stubFetcher);
expect(result.displayName).toBe('Alice');
});The default parameter lets production code work without passing fetcher explicitly, while tests inject a controlled version.
Property/Setter Injection
Assign the dependency after construction. Less clean but useful for optional dependencies or when retrofitting tests onto existing code.
class ReportGenerator:
def __init__(self):
self.formatter = DefaultFormatter() # sensible default
def generate(self, data):
return self.formatter.format(data)
# Test: replace the formatter after construction
def test_uses_custom_format():
generator = ReportGenerator()
generator.formatter = StubFormatter(output='custom output')
result = generator.generate({'key': 'value'})
assert result == 'custom output'Interface Segregation for Doubles
Keep dependency interfaces small. Large interfaces are hard to stub and hard to fake.
// Bad: one giant interface
interface DatabaseService {
query(sql: string): Promise<Row[]>;
execute(sql: string): Promise<void>;
transaction<T>(fn: () => Promise<T>): Promise<T>;
healthCheck(): Promise<boolean>;
getConnectionPool(): ConnectionPool;
// ... 15 more methods
}
// Good: split by use case
interface UserReader {
findById(id: string): Promise<User | null>;
findByEmail(email: string): Promise<User | null>;
}
interface UserWriter {
save(user: User): Promise<void>;
delete(userId: string): Promise<void>;
}
// UserService only needs UserReader + UserWriter
// Each test only stubs what the test usesA fake for UserReader has 2 methods. A fake for the 20-method DatabaseService takes a day to write.
Go: Interface-Based DI
Go's implicit interface implementation makes DI particularly clean.
// Define the interface your code needs
type UserRepository interface {
FindByID(ctx context.Context, id string) (*User, error)
Save(ctx context.Context, user *User) error
}
// Production implementation
type PostgresUserRepository struct {
db *sql.DB
}
func (r *PostgresUserRepository) FindByID(ctx context.Context, id string) (*User, error) {
// real database query
}
// Fake for tests
type FakeUserRepository struct {
users map[string]*User
}
func (r *FakeUserRepository) FindByID(ctx context.Context, id string) (*User, error) {
user, ok := r.users[id]
if !ok {
return nil, ErrNotFound
}
return user, nil
}
func (r *FakeUserRepository) Save(ctx context.Context, user *User) error {
r.users[user.ID] = user
return nil
}
// UserService depends on the interface
type UserService struct {
repo UserRepository
}
func NewUserService(repo UserRepository) *UserService {
return &UserService{repo: repo}
}
// Test
func TestGetUser_ReturnsNilOnMiss(t *testing.T) {
repo := &FakeUserRepository{users: make(map[string]*User)}
svc := NewUserService(repo)
user, err := svc.GetUser(context.Background(), "nonexistent")
assert.NoError(t, err)
assert.Nil(t, user)
}Go's interface system means any struct with the right methods satisfies the interface — no explicit implements declaration needed.
DI Containers: When to Use Them
DI frameworks (Spring, Angular's DI, Python's dependency_injector) wire up the dependency graph automatically. For testing, you typically bypass the container entirely.
// Spring: use @MockBean instead of wiring the container
@SpringBootTest
class OrderControllerTest {
@MockBean
private OrderService orderService; // Spring injects this mock
@Autowired
private MockMvc mockMvc;
@Test
void returnsOrderDetails() throws Exception {
when(orderService.getOrder("o1")).thenReturn(testOrder());
mockMvc.perform(get("/orders/o1"))
.andExpect(status().isOk())
.andExpect(jsonPath("$.id").value("o1"));
}
}For pure unit tests, don't use @SpringBootTest at all — construct the class directly with injected doubles. @SpringBootTest spins up the entire application context, which defeats the purpose of isolated unit testing.
The Testability Audit
If you're retrofitting tests onto existing code, run this audit:
- Find
newcalls inside constructors. Each one is a dependency that can't be replaced. Refactor to injection. - Find singleton access patterns.
getInstance(), global variables, module-level objects — these resist test doubles. Introduce interfaces and inject through constructors. - Find hidden I/O. File reads, HTTP calls, database queries buried in business logic. Extract into their own classes that can be injected.
- Find static method calls.
DateTime.now(),Math.random(),Logger.getLogger()— these are untestable I/O. Wrap them in injectable interfaces.
# Untestable: hidden I/O
class Scheduler:
def is_business_hours(self):
now = datetime.now() # can't control in tests
return 9 <= now.hour < 17
# Testable: inject the clock
class Scheduler:
def __init__(self, clock=None):
self.clock = clock or datetime
def is_business_hours(self):
now = self.clock.now()
return 9 <= now.hour < 17
# Test:
def test_is_not_business_hours_at_midnight(mocker):
fixed_clock = mocker.MagicMock()
fixed_clock.now.return_value = datetime(2026, 1, 1, 0, 0, 0)
scheduler = Scheduler(clock=fixed_clock)
assert not scheduler.is_business_hours()The DI+test-doubles combination is a design discipline, not just a testing technique. Code structured for testability is also code structured for change — dependencies are explicit, concerns are separated, and components can be swapped without cascading modifications.