Mocking static methods means creating fake versions of static methods to control their behavior during tests, allowing you to test code that depends on static methods without running the real ones.
Click to reveal answer
beginner
How do you start mocking static methods in Mockito 3.4+?
You use the try-with-resources block with Mockito.mockStatic(ClassName.class) to create a mock scope for static methods, ensuring the mock is closed after use.
Click to reveal answer
intermediate
Why should you use try-with-resources when mocking static methods?
Because it automatically closes the static mock after the test, preventing side effects on other tests and keeping tests isolated.
Click to reveal answer
beginner
What is the syntax to mock a static method call to return a specific value?
Inside the mockStatic block, use mockStatic.when(() -> ClassName.staticMethod(args)).thenReturn(value) to specify the fake return value.
Click to reveal answer
intermediate
Can you verify static method calls with Mockito 3.4+? How?
Yes, inside the mockStatic block, use mockStatic.verify(() -> ClassName.staticMethod(args)) to check if the static method was called as expected.
Click to reveal answer
Which Mockito feature allows mocking static methods starting from version 3.4+?
AMockito.spy()
BMockito.mock()
CMockito.when()
DMockito.mockStatic()
✗ Incorrect
Mockito.mockStatic() is the method introduced in Mockito 3.4+ to mock static methods.
Why is try-with-resources recommended when mocking static methods?
ATo automatically close the static mock and avoid side effects
BTo improve test speed
CTo mock instance methods
DTo create multiple mocks
✗ Incorrect
Try-with-resources ensures the static mock is closed after use, preventing interference with other tests.
How do you specify a return value for a mocked static method?
C. Missing try-with-resources block to close the static mock
D. Static method cannot be mocked in Mockito 3.4+
Solution
Step 1: Check static mock resource management
Static mocks must be closed; try-with-resources ensures this automatically.
Step 2: Identify missing try block
Code creates mock but does not close it, risking side effects.
Final Answer:
Missing try-with-resources block to close the static mock -> Option C
Quick Check:
Always use try-with-resources for static mocks [OK]
Hint: Always wrap static mocks in try-with-resources to auto-close [OK]
Common Mistakes:
Not closing static mocks causing test interference
Using wrong lambda syntax in when()
Mixing up assertEquals argument order
5. You want to test a method that calls Logger.log(), a static method, but you want to verify it was called exactly twice during the test. Which Mockito 3.4+ approach correctly achieves this?