0
0
JUnittesting~5 mins

Mocking static methods (Mockito 3.4+) in JUnit - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is mocking static methods in Mockito 3.4+?
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()
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
How do you specify a return value for a mocked static method?
AdoReturn(value).when(ClassName).staticMethod(args)
Bwhen(ClassName.staticMethod(args)).thenReturn(value)
Cverify(ClassName).staticMethod(args)
DmockStatic(ClassName).thenReturn(value)
Can you verify static method calls in Mockito 3.4+?
AOnly with Mockito 2.x
BNo, static methods cannot be verified
CYes, using verify() inside the mockStatic block
DYes, but only outside the mockStatic block
What happens if you don't close the static mock after testing?
AOther tests might be affected by the mock
BThe test will fail immediately
CThe static method will not be mocked
DMockito will throw an exception
Explain how to mock a static method using Mockito 3.4+ and why it is important to use try-with-resources.
Think about resource management and test isolation.
You got /4 concepts.
    Describe how to verify that a static method was called during a test using Mockito 3.4+.
    Verification is similar to instance method verification but inside the static mock scope.
    You got /3 concepts.