JUnit doNothing Example

In this tutorial we shall show users the usage of doNothing method. This method is basically resides inside the Mockito framework and is not a part of the JUnit.

1. Introduction

Many developers thought about the ways to test methods but do nothing about this. They might want to run the method only for the purpose of some other things that are related to that method. But directly there is no test required on that method itself.

Use doNothing() for setting void methods to do nothing.

Note: Beware that void methods on mocks do nothing by default.

There are rare situations when doNothing() comes handy. Sometimes is used in void return methods or to a method that does not have side effects, or is not related to the unit testing you are doing.

This is how definition of the doNothing() method looks like.

public static Stubber doNothing()

2. Project Dependencies

There are common things while we need to run or test the doNothing() example.

  • JUnit
  • Mockito

3. JUnit doNothing Example

Let’s take a small set of examples that use the doNothing() method. Examples below are taken from the Mockito framework. We need to add the following configurations to the project if we are using Maven.




Stubbing consecutive calls on a void method:

doNothing().doThrow(new RuntimeException()).when(mock).someVoidMethod();

//does nothing the first time:

//throws RuntimeException the next time:

Here calling the someVoidMethod() first it will do nothing. But on the consecutive call it will throw an error. When you spy real objects and you want the void method to do nothing:

List list = new LinkedList();
List spy = spy(list);

//let's make clear() do nothing


//clear() does nothing, so the list still contains "one"

In this example we are simply spying on the real object and we are doing some changes on that. But when we use doNothing() method, the real object will not change.

4. Conclusion

It is clear from this example that doNothing() is nothing but a method that will do nothing when applied to something. There are very limited uses of it as we have seen above. By default, all void methods in Mockito do nothing.

5. References

  1. JUnit Framework
  2. Mockito Framework

Vinod Kumar Kashyap

Vinod is Sun Certified and love to work in Java and related technologies. Having more than 13 years of experience, he had developed software's including technologies like Java, Hibernate, Struts, Spring, HTML 5, jQuery, CSS, Web Services, MongoDB, AngularJS, AWS. He is also a JUG Leader of Chandigarh Java User Group.
Notify of

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Inline Feedbacks
View all comments
Back to top button