Thursday, May 23, 2013

How to verify that void methods were called using Mockito

Mockito is one of the most popular mocking frameworks for java.
This post Is just little miscellaneous where I will show you how to mock and verify a void method call.

Sometimes when we test a call to a void method all we want to do is just make sure that at some point in its life cycle, another method will be called with certain parameters.
Let's see the following example:
 public class SomeClass {  
      private OtherClass otherClass;  
      public SomeClass(OtherClass otherClass) {  
           this.otherClass = otherClass;  
      protected void firstMethod(int value) {  
           if(value > 0) {  
           else {  
      private void secondMethod(String value) {  

In the above piece of legacy code the most important part is a method called "someMethod()". We must make sure that it is called in a proper way, but unfortunately it belongs to a dependency to which we have no access and also to make it more complicated it is inside a private method.

Mockito framework could help us mock and verify that method call.
Here is how we can do it:
 package demo;
 import static org.mockito.Mockito.verify;  
 import org.junit.Before;  
 import org.junit.Test;  
 import org.mockito.Mock;  
 import org.mockito.MockitoAnnotations;  
 import code.OtherClass;  
 import code.SomeClass;  
 public class TestClass {  
      private OtherClass otherClass;  
      //Class under test  
      private SomeClass someClass;  
      public void prepareDependencies() {  
           someClass = new SomeClass(otherClass);  
      public void is_the_value_greater_than_zero() {  
      public void is_the_value_smaller_than_zero() {  

The most important things to highlight in this test class are:
  • The class under test is never mocked.
  • The dependencies of the class under test need to be mocked.
  • By calling a method on a mock object we will mock that method call
  • By using the verify() method we will test that at some point the method from the mock was called  with the exact same parameters.
  • The test class can access the protected method because the package name is the same.(But of course in your project structure test will be under src/test/java and production code under src/main/java)


Share with your friends