Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to declare a mock object using the @Mock annotation.
JUnit
public class UserServiceTest { @[1] private UserRepository userRepository; }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using @InjectMocks instead of @Mock
Forgetting the '@' symbol
Using @Test annotation here
✗ Incorrect
The @Mock annotation is used to create a mock object for the UserRepository in the test class.
2fill in blank
mediumComplete the code to initialize mocks before running tests.
JUnit
@BeforeEach
public void setup() {
Mockito[1](this);
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using deprecated initMocks method
Misspelling the method name
Not calling any initialization method
✗ Incorrect
Mockito.openMocks(this) initializes the mock objects annotated with @Mock before each test.
3fill in blank
hardFix the error in the test method to use the mock correctly.
JUnit
@Test
public void testFindUser() {
when(userRepository.findById([1])).thenReturn(Optional.of(new User()));
User user = userService.findUserById(1);
assertNotNull(user);
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using a raw value '1' causing mismatch if argument differs
Using a string instead of integer
Passing null as argument
✗ Incorrect
Using anyInt() matcher allows the mock to respond to any integer argument, avoiding strict matching errors.
4fill in blank
hardFill both blanks to correctly verify the mock interaction.
JUnit
@Test
public void testSaveUser() {
User user = new User();
userService.saveUser(user);
verify(userRepository, [1]).save([2]);
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using never() instead of times(1)
Using any() instead of eq(user)
Omitting verify call
✗ Incorrect
verify(userRepository, times(1)).save(eq(user)) checks that save was called once with the exact user object.
5fill in blank
hardFill all three blanks to create a mock and inject it into the service under test.
JUnit
public class OrderServiceTest { @[1] private OrderRepository orderRepository; @[2] private OrderService orderService; @BeforeEach public void init() { Mockito.[3](this); } }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Mixing @Mock and @InjectMocks annotations
Using deprecated initMocks method
Forgetting to initialize mocks
✗ Incorrect
Use @Mock for the repository, @InjectMocks for the service, and Mockito.openMocks(this) to initialize mocks.