The @Mock annotation creates a mock object that simulates a real dependency. This allows testing the class in isolation without relying on actual implementations.
import org.junit.jupiter.api.Test; import org.mockito.Mock; import static org.mockito.Mockito.*; class ServiceTest { @Mock Repository repo; @Test void testService() { when(repo.getData()).thenReturn("mocked data"); System.out.println(repo.getData()); } }
The @Mock annotation alone does not create the mock instance unless Mockito is initialized (e.g., with @ExtendWith(MockitoExtension.class) or MockitoAnnotations.openMocks). Without initialization, the repo field is null, causing a NullPointerException when used.
mockList of type List, which assertion correctly verifies that the add("item") method was called exactly once?The verify(mockList, times(1)).add("item") assertion checks that the add method was called exactly once on the mock. Other options either misuse assertions or do not verify call counts.
import org.junit.jupiter.api.Test;
import org.mockito.Mock;
import static org.mockito.Mockito.*;
class UserServiceTest {
@Mock
UserRepository userRepository;
@Test
void testGetUser() {
when(userRepository.findUserById(1)).thenReturn(new User(1, "Alice"));
UserService service = new UserService(userRepository);
User user = service.getUser(1);
assertEquals("Alice", user.getName());
}
}The test fails because the @Mock annotation requires Mockito initialization (e.g., with MockitoExtension or MockitoAnnotations.openMocks). Without it, userRepository is null, causing NullPointerException when calling when().
@Mock annotations in a JUnit 5 test class using Mockito?In JUnit 5, the recommended way to activate Mockito annotations like @Mock is to annotate the test class with @ExtendWith(MockitoExtension.class). This initializes mocks automatically before each test.