Skip to content
intermediate Phase · Testing

Mocking

Replace external dependencies with mocks for isolated testing.

40m
0 problems
Topic Progress 0%

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

  1. Validation: Always validate input at the boundary
  2. Error Handling: Use structured error responses
  3. Logging: Log key events for debugging
  4. Testing: Unit, integration, and load tests
  5. Documentation: Keep docs updated with code changes

Practice Problems

0 / 3 solved
Implement Mocking

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
}
Mocking Edge Cases

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, idempotency
Mocking Testing Strategy

Write 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 injection

Quiz

1. @Mock creates?

Question 1 options

2. @InjectMocks does?

Question 2 options

3. What is a common mistake when implementing Mocking?

Question 3 options

Flashcards

Question

@Mock?

Answer

Creates fake object for testing

Question

@InjectMocks?

Answer

Creates real object with injected mocks

Question

Mocking best practices

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