Architecture & Testing · 8 min read · Beginner
Unit Testing OOP Classes with Fakes
Write fast, deterministic unit tests for object-oriented services by injecting lightweight in-memory fakes.
What you'll learn
- Structure tests with Arrange, Act, Assert (AAA)
- Test business logic cleanly using an in-memory fake repository
- Verify both happy paths and validation edge cases
Clean OOP pays its biggest dividend during unit testing. Because your service accepts its dependencies through the constructor (Dependency Injection), you can pass a 5-line in-memory fake instead of spinning up a real database or HTTP server.
Arrange, Act, Assert (AAA)
- Arrange: Instantiate the fake dependency and the service under test.
- Act: Call the method you want to verify.
- Assert: Check the return value or state stored in the fake.
Fill-in-the-Blank Exercise
Arrange-Act-Assert Test
Inject InMemoryRepo into UserService and assert that 1 user was saved.
const repo = new InMemoryRepo();
const svc = new UserService();
svc.register("ada@dev.io");
console.log(repo.items. === 1);Live OOP Playground
Unit Testing with an In-Memory Fake
Live Result
Console Output
No console output yet. Try calling console.log(...) in JS.
Check Your Understanding
Score: 0 / 1
1. Why do unit tests run much faster when you inject an in-memory fake repository?
Study Workspace
Finished this lesson?
Your progress is saved locally in your browser, no account needed.