0
0
JUnittesting~5 mins

@InjectMocks annotation in JUnit - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is the purpose of the @InjectMocks annotation in JUnit testing?
<p>The <code>@InjectMocks</code> annotation is used to create an instance of the class under test and inject mock dependencies into it automatically.</p>
Click to reveal answer
beginner
How does @InjectMocks differ from @Mock in JUnit tests?

@Mock creates mock objects for dependencies, while @InjectMocks creates the real object and injects those mocks into it.

Click to reveal answer
intermediate
Which injection types does @InjectMocks support for injecting mocks?

@InjectMocks supports constructor injection, setter injection, and field injection to insert mocks into the tested class.

Click to reveal answer
intermediate
What happens if @InjectMocks cannot find a suitable constructor or setter to inject mocks?
<p>The injection will fail silently, and the tested class may have null dependencies, causing NullPointerExceptions during test execution.</p>
Click to reveal answer
beginner
Can @InjectMocks be used without initializing mocks with MockitoAnnotations.openMocks(this) or @ExtendWith(MockitoExtension.class)?

No. To enable @InjectMocks to work, mocks must be initialized either by calling MockitoAnnotations.openMocks(this) in a setup method or using the Mockito extension with JUnit 5.

Click to reveal answer
What does the @InjectMocks annotation do in a JUnit test?
ARuns the test method multiple times
BCreates mock objects for dependencies
CCreates a real instance of the class and injects mocks into it
DMocks static methods
Which of the following is NOT a way @InjectMocks injects mocks?
AConstructor injection
BSetter injection
CField injection
DInterface injection
What must you do to enable @InjectMocks to work properly in your test class?
AInitialize mocks with <code>MockitoAnnotations.openMocks(this)</code> or use <code>@ExtendWith(MockitoExtension.class)</code>
BCall <code>System.out.println()</code> in the test
CUse <code>@Test</code> annotation only
DWrite a main method
If @InjectMocks cannot find a suitable constructor or setter, what is likely to happen?
AMocks will be injected anyway
BDependencies will remain null, causing errors
CTest will pass without any issue
DJUnit will skip the test
Which annotation is used to create mock objects that @InjectMocks will inject?
A@Mock
B@Test
C@BeforeEach
D@Spy
Explain how @InjectMocks works in a JUnit test and why it is useful.
Think about how it helps avoid writing manual code to set dependencies.
You got /4 concepts.
    Describe the steps needed to properly use @InjectMocks in a test class.
    Consider both annotations and mock initialization.
    You got /4 concepts.