Practice - 5 Tasks
Answer the questions below
1fill in blank
easyComplete the code to create a mock object for the dependency.
JUnit
@Mock
private Service [1]; Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using the class name instead of a variable name.
Adding prefixes like 'mock' unnecessarily.
✗ Incorrect
The field name 'service' is used to declare the mock object for the Service class.
2fill in blank
mediumComplete the code to inject mocks into the tested class.
JUnit
@InjectMocks
private [1] controller; Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using the variable name instead of the class type.
Confusing the service class with the controller class.
✗ Incorrect
The tested class type is 'Controller', and the variable name is 'controller'.
3fill in blank
hardFix the error in the test setup method to initialize mocks.
JUnit
@BeforeEach
void setUp() {
MockitoAnnotations.[1](this);
} Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using deprecated initMocks method.
Calling mockStatic instead of initializing instance mocks.
✗ Incorrect
Since Mockito 3.4.0, MockitoAnnotations.openMocks(this) is the recommended way to initialize mocks.
4fill in blank
hardFill both blanks to correctly declare and inject mocks for dependencies.
JUnit
@Mock private [1] repository; @InjectMocks private [2] service;
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using variable names instead of class types for mocks.
Mixing up the order of mock and injectMocks declarations.
✗ Incorrect
The mock is declared with the class type 'Repository' and injected into the 'Service' class.
5fill in blank
hardFill all three blanks to complete the test class setup with mocks and injection.
JUnit
class UserServiceTest { @Mock private [1] userRepository; @InjectMocks private [2] userService; @BeforeEach void init() { MockitoAnnotations.[3](this); } }
Drag options to blanks, or click blank then click option'
Attempts:
3 left
💡 Hint
Common Mistakes
Using deprecated initMocks instead of openMocks.
Mixing variable names with class types in annotations.
✗ Incorrect
Mocks are declared with UserRepository, injected into UserService, and initialized with MockitoAnnotations.openMocks(this).