Test Isolation with Doubles: Best Practices

Test Isolation with Doubles: Best Practices

Test isolation means your unit test only fails when the unit under test has a bug — not when a database is slow, a third-party API is down, or a collaborator class has a bug. Test doubles (mocks, stubs, fakes, spies) are the primary tool for achieving this.

But isolation done wrong gives you a false sense of security. Here's how to do it right.

Why Isolation Matters

A unit test that isn't isolated is a slow, flaky integration test in disguise. Consider:

def test_user_registration():
    # This hits the real database, real email server, real analytics API
    result = register_user(email='test@example.com', password='pass123')
    assert result.id is not None

This test will fail if:

  • The database is down
  • The email server rejects the connection
  • The analytics API rate-limits you
  • Another test left dirty data in the database
  • The database is running but slow (test timeout)

None of these failures indicate a bug in register_user. Yet all of them will wake someone up at 3am.

The Isolation Boundary

The key decision in any unit test: what is the unit, and where are its boundaries?

For a UserService class:

  • Inside the unit: the logic in UserService methods
  • At the boundary: UserRepository, EmailService, AnalyticsClient
  • Outside the unit: actual database, actual SMTP server, actual analytics endpoint

Replace everything at or beyond the boundary. Don't replace anything inside the unit — if you do, you're not testing the unit anymore.

class UserService:
    def __init__(self, user_repo, email_service, analytics):
        self.user_repo = user_repo      # boundary: stub/mock this
        self.email_service = email_service  # boundary: stub/mock this
        self.analytics = analytics      # boundary: stub/mock this

    def register(self, email, password):
        # This logic is what you're testing
        if not self._validate_email(email):
            raise ValueError("Invalid email")
        
        user = User(email=email, password_hash=hash_password(password))
        self.user_repo.save(user)
        self.email_service.send_welcome(email)
        self.analytics.track('user_registered', {'email': email})
        return user

Dependency Injection: The Prerequisite

You can't replace dependencies without dependency injection. If your code creates its own dependencies, you can't isolate it:

# Bad: untestable — UserService owns its dependencies
class UserService:
    def __init__(self):
        self.db = PostgresConnection(host='prod-db')  # can't replace this
        self.mailer = SMTPMailer(host='smtp.mailgun.org')  # can't replace this
# Good: testable — dependencies injected
class UserService:
    def __init__(self, user_repo, mailer):
        self.user_repo = user_repo
        self.mailer = mailer

In production: pass real implementations. In tests: pass doubles.

Choosing the Right Double

Situation Double type
Dependency returns data your unit needs Stub
You need to verify a call was made Mock
Dependency has real behavior you need Fake
You want to observe calls without intercepting Spy
Dependency raises an exception you need to handle Stub with side_effect

Best Practice: One Double Per Concern

Each test should set up doubles for exactly what that test needs.

# Bad: every test sets up every dependency
@pytest.fixture
def user_service(mocker):
    mocker.patch('myapp.repos.UserRepo.save')
    mocker.patch('myapp.repos.UserRepo.find')
    mocker.patch('myapp.mailer.Mailer.send_welcome')
    mocker.patch('myapp.mailer.Mailer.send_password_reset')
    mocker.patch('myapp.analytics.Analytics.track')
    return UserService()

# Each test inherits a cluttered setup with irrelevant doubles
def test_registration_validates_email(user_service):
    with pytest.raises(ValueError):
        user_service.register(email='not-an-email', password='pass')
    # This test doesn't care about the mailer or analytics at all
# Better: each test sets up only what it needs
def test_registration_validates_email(mocker):
    repo_stub = mocker.patch('myapp.repos.UserRepo.save')
    mailer_stub = mocker.patch('myapp.mailer.Mailer.send_welcome')
    analytics_stub = mocker.patch('myapp.analytics.Analytics.track')
    
    service = UserService(repo_stub, mailer_stub, analytics_stub)
    
    with pytest.raises(ValueError):
        service.register(email='not-an-email', password='pass')
    # Only asserts on the ValueError; doubles are ignored

The difference matters when tests fail: you immediately see what the test was actually testing.

Don't Isolate the Test Into Meaninglessness

Over-isolation is a real problem. If you stub everything, you end up testing nothing.

// This test is useless — it just tests that the mock returns what you told it to
test('getTotal returns total', () => {
  const mockCart = { getTotal: jest.fn().mockReturnValue(100) };
  expect(mockCart.getTotal()).toBe(100);
});

The test passed before the code was even written. It will keep passing if the real getTotal is broken. Stubs and mocks replace collaborators, not the unit under test.

Handling Error Scenarios

Stubs make it easy to test error paths that would be painful to trigger with real dependencies.

def test_handles_db_failure_gracefully(mocker):
    repo_mock = mocker.patch('myapp.repos.UserRepo.save')
    repo_mock.side_effect = DatabaseConnectionError("Connection refused")
    
    mailer_stub = mocker.MagicMock()
    analytics_stub = mocker.MagicMock()
    
    service = UserService(repo_mock, mailer_stub, analytics_stub)
    
    with pytest.raises(ServiceUnavailableError):
        service.register('alice@example.com', 'pass123')
    
    # Verify the mailer was NOT called if DB failed
    mailer_stub.send_welcome.assert_not_called()

Without test doubles, triggering a DatabaseConnectionError requires either taking down your DB or adding complex test infrastructure.

Isolation Doesn't Mean No Integration Tests

Isolated unit tests are fast and reliable, but they don't prove your components work together. You still need integration tests — just not mixed in with your unit tests.

The separation:

  • Unit tests (isolated): test logic, run in milliseconds, run on every commit
  • Integration tests (real dependencies): test wiring, run in seconds, run pre-merge or nightly

If you're using HelpMeTest for end-to-end monitoring, your integration tests belong in a separate suite that runs against a staging environment, not in the same CI step as your unit tests.

Practical Checklist

Before writing a test, confirm:

  • Dependencies are injected (not created inside the unit)
  • Each test only stubs/mocks what it needs
  • Assertions are on the unit's behavior, not on the doubles' internals
  • Error paths have explicit tests using side_effect or equivalent
  • You have at least one integration test that uses real dependencies end-to-end

Test isolation is a design discipline. If your code is hard to isolate, that's the code telling you it needs to be refactored — not a sign you need more elaborate test setup.

Read more

Start now free