Module 2: Mockito (The Stunt Double)
📚 Module 2: Mockito (The Stunt Double)
Focus: Moving from “Real dependencies” to “Fake partners.”
What if you want to test a Service, but that service needs to talk to a Database that hasn’t been built yet? Or an Email Server that costs money every time you send a test email? We use Mockito to create fakes.
🏗️ Step 1: The Problem (The “Expensive” Dependency)
Imagine you are filming a movie.
- You have a scene where the main actor jumps off a 50-story building.
- You don’t want to use the real actor (The real Database) because if it fails, the actor is destroyed!
🏗️ Step 2: Mocks (The “Stunt Double”)
Mockito allows you to create a Stunt Double (a Mock) for your objects.
🧩 The Analogy: The Dummy
- Instead of using a real bank account with real money, you use a Plastic Credit Card.
- You tell the plastic card: “When someone asks for your balance, say ‘$1,000,000’.”
- The card doesn’t have a real brain; it just follows your instructions.
In Code:
@Test
public void testProductService() {
// 1. Create a "Stunt Double" for the database
ProductRepository mockRepo = mock(ProductRepository.class);
// 2. Tell the double how to behave
when(mockRepo.findById(1L)).thenReturn(Optional.of(new Product("Mock Laptop")));
// 3. Test your service using the double
ProductService service = new ProductService(mockRepo);
String name = service.getProductName(1L);
assertEquals("Mock Laptop", name);
}🏗️ Step 3: Why use Mockito?
- Isolation: You are testing YOUR code, not the database’s code.
- Reliability: Mocks never fail because of a slow internet connection.
- Speed: Mocks live in memory and are 1,000,000x faster than a real database.
🥅 Module 2 Review
- Mock: A fake object that simulates the behavior of a real one.
- Stubbing: Telling the mock how to answer (
when(...).thenReturn(...)). - Verification: Checking if the mock was actually called (
verify(...)). - Mockito: The most popular mocking library in the Java world.