Effective Mockito Part 4

October 17, 2011 | 3 min Read

This Effective Mockito Post will be IDE specific again but related to the last post on Mockito’s spies. If you’ve read Part 3 you should now be familiar how to use them to “pseudo mock” statics. When writing code it often comes to a point where we want to debug using single step debugging. When using Mockito and especially when spies come into the game there is still something pretty annoying.

That is, when we want to debug our Object-Under-Test’s real method and the object is a spy. When we try to step into the object’s method we always land in internal Mockito code. After a little reading we can drill deeper but the next landing place is in java.lang.reflect code and so on. To be honest, this is really not the nicest way to debug code. What I want is that regardless of whether I use spies or not, when I step into an object’s method I land directly in this method. In the past my workaround was to set a breakpoint in the test at the method call and in the method itself. This enabled me to stop at the first point and resume the execution until it stops the second time in the method. But there is a much more elegant way. Let’s see how we can do this.

First of all, let’s take a look at an example. The code below shows a simple test from the last Effective Mockito post. The test uses a spy to “pseudo mock” a static method. We set a breakpoint in the line of the isPropertySet call and debug this method. Sadly when doing this we run into the effect described above.

@RunWith( MockitoJUnitRunner.class )
public class MyObjectText {
  
  @Spy
  private MyObject objectUnderTest;
  
  @Test
  public void testIsPropertySet() {
    doReturn( "some runtime property" ).when( objectUnderTest ).getProperty();

    boolean isPropertySet = objectUnderTest.isPropertySet();
    
    assertFalse( isPropertySet );
  }
  
}

When using Eclipse there is a very simple way to avoid this called “Step Filtering”. We can add packages or classes to this Filterlist using the preferences. When filters are activated the classes will automatically be skipped during debugging. By setting a filter like the one in the screenshot below we can simply step over the Mockito and reflection code.

If you are not using Eclipse there is probably a similar way to achieve this with your IDE. It would be cool if you would share this tip with us in a comment. Meantime, I hope that Step Filtering is as helpful to you as it is for me.  Finally, I want to thank Fluffi and Frank for getting me to dive into this.

Follow @hstaudacher

Read the other Effective Mockito posts: