Mock verify interactions (assertions), Stub cung cấp canned responses, Spy observe real implementation, Fake có working implementation đơn giản — overcrowded mocks là code smell, thường báo hiệu SRP violation.
- Test doubles là các loại replacements cho real dependencies trong tests — Martin Fowler phân loại trong 'Mocks Aren't Stubs'.
- Dummy: placeholder object được pass vào nhưng không bao giờ thực sự được dùng — ví dụ pass null hoặc empty object để fulfill parameter requirement.
- Stub: trả về pre-configured responses cho calls — không verify interactions, chỉ provide canned answers; ví dụ stub database trả về fixed user object.
- Mock: pre-programmed với expectations về calls mà nó sẽ nhận — verify những interactions này xảy ra; jest.fn() là mock vì có thể assert toHaveBeenCalledWith(); test fail nếu expected calls không xảy ra.
- Spy: wrap real implementation, record calls — jest.spyOn() by default calls real method, ghi lại arguments; có thể override với mockImplementation khi cần.
- Fake: có working implementation đơn giản hơn real — fake in-memory database (Map<id, entity>), fake email service (lưu emails vào array thay vì gửi thật), fake message queue.
- Practical guidance: dùng Stub khi cần control return values; Mock khi muốn verify behavior (dùng đúng dependencies đúng cách); Spy khi muốn observe real implementation; Fake khi cần realistic behavior nhưng không thể/không muốn dùng real service.
- Overcrowded mocks là code smell: nếu test cần mock quá nhiều dependencies, code đang vi phạm Single Responsibility Principle — refactor code, không thêm mocks.