0
0
JUnittesting~10 mins

Mocking static methods (Mockito 3.4+) 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 start mocking static methods using Mockito.

JUnit
try (MockedStatic<Utility> utilities = Mockito.[1](Utility.class)) {
    // test code
}
Drag options to blanks, or click blank then click option'
AmockStatic
BwhenStatic
CstaticMock
DmockStaticMethod
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'whenStatic' instead of 'mockStatic'.
Trying to mock static methods without using try-with-resources.
2fill in blank
medium

Complete the code to stub a static method to return a specific value.

JUnit
utilities.[1](() -> Utility.staticMethod()).thenReturn("mocked value");
Drag options to blanks, or click blank then click option'
AdoReturn
Bwhen
Cstub
Dmock
Attempts:
3 left
💡 Hint
Common Mistakes
Using 'doReturn' which is for instance methods.
Trying to stub without a lambda expression.
3fill in blank
hard

Fix the error in the code to verify a static method was called once.

JUnit
utilities.verify(() -> Utility.staticMethod(), [1]);
Drag options to blanks, or click blank then click option'
Aonce()
BcalledOnce()
Ctimes(1)
DverifyOnce()
Attempts:
3 left
💡 Hint
Common Mistakes
Using non-existent methods like 'calledOnce' or 'once'.
Omitting the verification mode argument.
4fill in blank
hard

Fill both blanks to mock two different static methods with different return values.

JUnit
utilities.[1](() -> Utility.firstStatic()).thenReturn(10);
utilities.[2](() -> Utility.secondStatic()).thenReturn(20);
Drag options to blanks, or click blank then click option'
Awhen
BdoReturn
Cstub
Dmock
Attempts:
3 left
💡 Hint
Common Mistakes
Using different stubbing methods inconsistently.
Trying to stub without lambda expressions.
5fill in blank
hard

Fill all three blanks to correctly open, stub, and close the static mock.

JUnit
try (MockedStatic<Utility> utilities = Mockito.[1](Utility.class)) {
    utilities.[2](() -> Utility.staticMethod()).thenReturn("done");
} // [3] closes the mock automatically
Drag options to blanks, or click blank then click option'
AmockStatic
Bwhen
Ctry-with-resources
Dclose
Attempts:
3 left
💡 Hint
Common Mistakes
Forgetting to use try-with-resources to close the mock.
Using incorrect methods to open or stub the mock.