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: doNothing().when(mockObject).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()
✗ 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?
AIt causes a compilation error
BIt throws an exception at runtime
CIt works normally
DIt silently ignores the call
✗ 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?