0
0
JUnittesting~5 mins

Mocking void methods in JUnit - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What is a void method in Java?
A void method is a method that does not return any value. It performs an action but returns nothing.
Click to reveal answer
beginner
Why do we need to mock void methods in unit testing?
We mock void methods to control their behavior during tests, especially if they cause side effects or interact with external systems, so tests can run reliably and independently.
Click to reveal answer
intermediate
How do you mock a void method using Mockito in JUnit?
Use Mockito's doNothing(), doThrow(), or doAnswer() methods with when() to define behavior for void methods. For example: <br> doNothing().when(mockObject).voidMethod();
Click to reveal answer
intermediate
What does the following code do?<br>
doThrow(new RuntimeException()).when(mockService).voidMethod();
It tells Mockito to throw a RuntimeException when the voidMethod() is called on mockService during the test.
Click to reveal answer
intermediate
Explain the difference between when() and doNothing() when mocking void methods.
when() cannot be used directly with void methods because they return nothing. Instead, doNothing() is used to specify that the void method should do nothing when called during the test.
Click to reveal answer
Which Mockito method is used to mock a void method that should do nothing when called?
AdoNothing()
Bwhen()
CthenReturn()
Dverify()
What happens if you try to use when() directly on a void method in Mockito?
AIt causes a compilation error
BIt throws an exception at runtime
CIt works normally
DIt silently ignores the call
How can you make a mocked void method throw an exception when called?
Awhen(mock.voidMethod()).thenThrow(new Exception());
BdoNothing().when(mock).voidMethod();
CdoThrow(new Exception()).when(mock).voidMethod();
Dverify(mock).voidMethod();
What is the purpose of mocking void methods in unit tests?
ATo test the return value
BTo increase code complexity
CTo avoid writing tests
DTo control side effects and interactions
Which of the following is NOT a valid way to mock a void method in Mockito?
AdoNothing()
BthenReturn()
CdoThrow()
DdoAnswer()
Describe how to mock a void method in JUnit using Mockito and explain why this is useful.
Think about how void methods behave and how Mockito handles them differently.
You got /4 concepts.
    Explain the difference between mocking a void method and a method that returns a value.
    Focus on how Mockito syntax changes based on method return type.
    You got /4 concepts.