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

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.

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.

Last updated: 16 July 2026

Previous question: What is Mockito, and why is it used in unit testing?

Next question: What is the purpose of the @Mock and @InjectMocks annotations?

More Mockito interview questions

All Mockito questions