0
0
JUnittesting~10 mins

@Mock annotation in JUnit - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete 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'
AMock
BInjectMocks
CAutowired
DTest
Attempts:
3 left
💡 Hint
Common Mistakes
Using @InjectMocks instead of @Mock
Forgetting the '@' symbol
Using @Test annotation here
2fill in blank
medium

Complete 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'
AcreateMocks
BinitMocks
CstartMocks
DopenMocks
Attempts:
3 left
💡 Hint
Common Mistakes
Using deprecated initMocks method
Misspelling the method name
Not calling any initialization method
3fill in blank
hard

Fix 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'
A1
BanyInt()
C"1"
Dnull
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
4fill in blank
hard

Fill 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'
Atimes(1)
Bany()
Cnever()
Deq(user)
Attempts:
3 left
💡 Hint
Common Mistakes
Using never() instead of times(1)
Using any() instead of eq(user)
Omitting verify call
5fill in blank
hard

Fill 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'
AMock
BInjectMocks
CopenMocks
DBefore
Attempts:
3 left
💡 Hint
Common Mistakes
Mixing @Mock and @InjectMocks annotations
Using deprecated initMocks method
Forgetting to initialize mocks