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?
✗ Incorrect
doNothing() is used to mock void methods to do nothing when called.
What happens if you try to use when() directly on a void method in Mockito?
✗ Incorrect
Using when() directly on void methods causes a compilation error because void methods do not return values.
How can you make a mocked void method throw an exception when called?
✗ Incorrect
doThrow() is used with when() to specify that a void method should throw an exception.
What is the purpose of mocking void methods in unit tests?
✗ Incorrect
Mocking void methods helps control side effects and external interactions during tests.
Which of the following is NOT a valid way to mock a void method in Mockito?
✗ Incorrect
thenReturn() cannot be used with void methods because they do not return values.
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.