How to Use doNothing in Mockito with JUnit Tests
In Mockito with JUnit, use
doNothing() to stub void methods that you want to ignore during testing. It tells Mockito to do nothing when the method is called, avoiding side effects or exceptions. Use it with doNothing().when(mock).voidMethod() syntax.Syntax
The doNothing() method is used to stub void methods in Mockito. It is combined with when() to specify which method call should do nothing.
doNothing(): Tells Mockito to do nothing when the stubbed method is called.when(mock).voidMethod(): Specifies the void method on the mock object to stub.
java
doNothing().when(mockObject).voidMethod();
Example
This example shows how to use doNothing() to stub a void method sendEmail() in a mocked EmailService. The test verifies that the method is called without throwing exceptions or performing real actions.
java
import static org.mockito.Mockito.*; import org.junit.jupiter.api.Test; class EmailService { void sendEmail(String recipient) { // Actual sending logic System.out.println("Sending email to " + recipient); } } public class EmailServiceTest { @Test void testSendEmailDoesNothing() { EmailService mockEmailService = mock(EmailService.class); // Stub sendEmail to do nothing doNothing().when(mockEmailService).sendEmail(anyString()); // Call the method mockEmailService.sendEmail("user@example.com"); // Verify it was called once verify(mockEmailService, times(1)).sendEmail("user@example.com"); } }
Common Pitfalls
Common mistakes when using doNothing() include:
- Trying to use
when(mock.voidMethod()).thenReturn()which does not work for void methods. - Not using
doNothing()withwhen()syntax for void methods. - Forgetting to verify the method call if you want to check interaction.
Correct usage requires doNothing().when(mock).voidMethod() instead of when(mock.voidMethod()).thenReturn().
java
/* Wrong way - causes compilation error or runtime exception */ // when(mockEmailService.sendEmail(anyString())).thenReturn(null); // invalid for void /* Right way */ doNothing().when(mockEmailService).sendEmail(anyString());
Quick Reference
Use doNothing() to stub void methods that should not perform any action during tests. Combine it with when() and the mock method call. Always verify calls if needed.
| Usage | Description |
|---|---|
| doNothing().when(mock).voidMethod(); | Stub void method to do nothing when called |
| verify(mock).voidMethod(); | Check that the void method was called |
| doThrow(exception).when(mock).voidMethod(); | Stub void method to throw exception |
Key Takeaways
Use doNothing() with when() to stub void methods in Mockito.
doNothing() prevents side effects or exceptions from void methods during tests.
Never use thenReturn() with void methods; it causes errors.
Always verify void method calls if you want to check interactions.
doNothing() is useful for ignoring void methods that have no test impact.