How do you mock an object in Mockito?

Mocking an object in Mockito means creating a fake implementation of a class or interface using mock(), which returns default values unless you explicitly configure its behavior.

Key Points: • Call mock(SomeClass.class) to get a fake instance with no real logic. • Configure return values with when(mockObj.method()).thenReturn(value). • Configure exceptions with when(mockObj.method()).thenThrow(exception). • Unconfigured methods return type-appropriate defaults (null, 0, false, empty collections) rather than throwing. • The @Mock annotation combined with MockitoExtension is a shorthand for the same thing in annotated test classes.

Example: Mocking a UserRepository with mock(UserRepository.class) and stubbing findById() to return a fixed User lets you test a UserService without a real database.

Code Example:

UserRepository repo = mock(UserRepository.class);
when(repo.findById(1L)).thenReturn(Optional.of(new User("Alice")));

UserService service = new UserService(repo);
assertEquals("Alice", service.getUserName(1L));

Interview Tip: A concise interview answer is:

"I create a mock with mock(SomeClass.class), which gives me a fake object returning default values for every method until I stub specific behavior with when()/thenReturn(). It lets me test code that depends on that object without needing the real implementation."