Mocking
Mockito Example
@ExtendWith(MockitoExtension.class)
class OrderServiceTest {
@Mock
private OrderRepository repository;
@Mock
private PaymentService paymentService;
@InjectMocks
private OrderService service;
@Test
void shouldCreateOrder() {
when(repository.save(any())).thenAnswer(inv -> inv.getArgument(0));
Order order = service.create(new OrderRequest("laptop", 999.99));
verify(repository).save(any(Order.class));
verify(paymentService).charge(any(), anyDouble());
}
}
Mocking Strategies
Mock Types
- Stub: Returns predefined data
- Mock: Verifies interactions
- Spy: Partial mock
When to Mock
- External services
- Database connections
- Time-dependent code
- Random number generation
Best Practices
- Don't over-mock
- Verify behavior, not implementation
- Use dependency injection
- Clean up after tests
Key Points
- Understanding Mocking is essential for production systems
- Always consider scalability and maintainability
- Test thoroughly before deploying to production
- Monitor performance and set up alerting
Common Patterns
- Validation: Always validate input at the boundary
- Error Handling: Use structured error responses
- Logging: Log key events for debugging
- Testing: Unit, integration, and load tests
- Documentation: Keep docs updated with code changes
Practice Problems
Design and implement a solution for Mocking in a backend system. Consider scalability, error handling, and production readiness.
Solution
// Mocking implementation
// Key aspects: validation, error handling, logging, testing
public class Mocking {
// Production-ready implementation
}Identify and handle edge cases for Mocking. What happens under high load, with invalid input, or during failures?
Solution
// Edge case handling:
// 1. Null/empty input -> validation
// 2. High load -> rate limiting, queuing
// 3. Failures -> retries, circuit breaker
// 4. Concurrent access -> locks, idempotencyWrite a testing strategy for Mocking. Include unit tests, integration tests, and performance tests.
Solution
// Test plan:
// - Unit: 80% coverage target
// - Integration: API contracts
// - Performance: latency, throughput
// - Chaos: failure injectionQuiz
1. @Mock creates?
2. @InjectMocks does?
3. What is the primary purpose of Mocking?
4. What is a common mistake when implementing Mocking?
Flashcards
Question
@Mock?
Click to reveal answer
Answer
Creates fake object for testing
Question
@InjectMocks?
Click to reveal answer
Answer
Creates real object with injected mocks
Question
What is Mocking?
Click to reveal answer
Answer
Mocking is a key concept in backend development.
Question
When to use Mocking?
Click to reveal answer
Answer
Use Mocking when building production systems that require reliability, scalability, and maintainability.
Question
Mocking best practices
Click to reveal answer
Answer
Follow SOLID principles, write clean code, test thoroughly, document decisions, and monitor in production.
Revision Notes
Key Takeaways
- 1.Mocking: fake objects you control
- 2.@Mock creates mock, @InjectMocks injects
- 3.when().thenReturn() for stubbing
- 4.verify() checks interactions
Interview Tips
- •Use Mockito for mocking
- •Know stubbing and verification
Cheat Sheet
Mocking
- @Mock: fake object
- @InjectMocks: inject mocks
- when().thenReturn(): stub
- verify(): check interactions