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

Fakes: Working Implementations for Testing

Building simplified but functional implementations like in-memory databases that behave realistically in tests.

Fakes: Working Implementations for Testing

You'll learn how to create simplified but fully functional implementations that make testing easier and faster.

What is a Fake?

A fake is a test double that actually works—it's a real, functioning implementation, just simpler than the production version. Unlike stubs that return hard-coded values, fakes have genuine logic and maintain state.

Think of it like a movie set: instead of filming in an actual bank with real security systems and vault doors, you build a convincing fake bank with working doors that open and close. The fake bank functions realistically for filming purposes, but it's much simpler and safer than the real thing.

Common Examples

The most common fake is an in-memory database. Instead of connecting to PostgreSQL or MySQL during tests, you use an in-memory data structure that supports the same operations (add, find, update, delete) but stores everything in memory.

class FakeUserRepository:
    def __init__(self):
        self.users = {}  # In-memory storage
        self.next_id = 1
    
    def save(self, user):
        if not user.id:
            user.id = self.next_id
            self.next_id += 1
        self.users[user.id] = user
        return user
    
    def find_by_id(self, user_id):
        return self.users.get(user_id)

When to Use Fakes

Use fakes when:

  • The real implementation is too slow (database, network, file system)
  • You need realistic behavior with state and side effects
  • Stubs are too simplistic for the test scenario
  • The fake is reasonably simple to build and maintain

Key Takeaway: Fakes are working implementations designed for testing—they behave realistically but are simpler, faster, and more controllable than production code.