Mocking Java

Oct 15,2017 at 12:57 pm By Ben Hutton

While you can argue for or against Mocking Java (or any other language) it can at times be an advantage.  For example a recent project I have been working on I wanted to test code within the paint() method in Java.  Now to the best of my knowledge you cannot externally run this method as it requires an argument to be passed in that cannot be met normally.

This is where Mocking comes into play.  Whether testing the Graphics library with Java or testing the logic of OS System calls it can be very useful.  It can however get overused largely due to code that is not designed with testing in mind.  At least that’s what I’ve found when trying the TDD approach on an existing non TDD code base.

The mocking library I have been using is Mockito.  You can build this yourself of just go the this link.  Once downloaded you can use it like so:

Configure Mockito in your IDE

For IntelliJ find your Project.iml file and add an entry like the follow:

<orderEntry type="module-library">
 <library name="mockito-all-1.10.19.jar">
 <CLASSES>
 <root url="jar://$MODULE_DIR$/mockito-all-1.10.19.jar!/" />
 </CLASSES>
 <JAVADOC />
 <SOURCES />
 </library>
</orderEntry>

 

For Eclipse you can add it to your Project Properties.  You can get that by right clicking on the top level of the Project tree and selecting Properties.

 

Java, TDD and Mocking Graphics

 

And now for the coding part

Once you have Mockito running all you have to do is something like the below example of code.

 

import static org.mockito.Mockito.*;

public class MyTestClass {
  
   private MyClass mc = new MyClass();
   Graphics g = mock(Graphics.class); 

   @Test public void testPaint() { 
      mc.paint(g); 
   } 
}

 

All you have to do now is run your tests…

Leave a comment

Login to Comment

Copyright © 2017 | Ben Hutton