What is mocking in unit testing?

Answer

Mocking is creating controlled test doubles that simulate the behavior of real dependencies, allowing unit tests to run in isolation without actual databases, network calls, or external services. Benefits: (1) Speed — tests run in milliseconds instead of seconds. (2) Reliability — no flaky tests due to network issues or database state. (3) Isolation — test one unit without testing its dependencies simultaneously. (4) Control — simulate edge cases (network timeout, specific error responses) that are hard to reproduce with real services. Example in Jest: jest.mock('./userService'); userService.getUser.mockResolvedValue({ id: 1, name: 'Alice' });. In Moq (C#): var mockRepo = new Mock<IUserRepository>(); mockRepo.Setup(r => r.GetById(1)).Returns(new User { Name = "Alice" });. Rule of thumb: mock things you don't own (external services, databases), use real implementations for things you own (your own services, domain logic).