In general I prefer to wrap up system functions so that I can inject test doubles and test drive my designs easily. In general is not a good idea to mock objects you don’t own. But this time I was doing some research, preparing one edition of my Online Training Class on Test Doubles and came across jMockit as a way to stub out System artifacts. jMockit is an isolation framework that I haven’t tried before.

The idea is to stub the System.currentTimeMillis built-in function. I tried PowerMock but it didn’t work for this particular case. PowerMock is brilliant for stubbing static methods and constructors as long as they are not part of the system. Very handy for legacy code.

// import mockit.*;
public void simulateCurrentTime() {
 new Expectations() { 
	 @Mocked("currentTimeMillis") System mockedSystem;
	 { 
	     System.currentTimeMillis(); 
             result = 123456L; 
        }}; 
}

This is the method I had to invoke from within my JUnit test in order to stub out the function. It works! I have to say that it took me more than one hour to make it work because I couldn’t find this in the documentation. I found several blog posts but they are old, the framework has changed since then. Eventually, a combination of information gathered from several posts yielded this working method.

Kids, don’t do this at home!

If you want to know more, join the next edition of my training class 😉