yoshi594
yoshi594

Reputation: 61

Mocking the current time with JRE 1.4

I'm currently restricted to only using JRE 1.4 (java runtime environment) and i have a class which has some current time calculations. I am trying to unit test the class but it seems quite hard as all the mocking tools that i have encountered require annotations which aren't support by JRE1.4.

I'd tried using a JRE 1.4 friendly version of mockito but that does not allow me to mock out static classes. Jmockit has a super easy solution that's available to download BUT there doesn't seem to be a JRE1.4 friendly version of Jmockit

There's two ways i could have gotten around this if i were using JRE1.5 and above (mock out the method that calls for current time or just mock out the current system time), but sadly i am not.

The only solution for this is to just pass the current system time into the methods with +/- a day/month/year.

I would however like to do it the mocking way if possible under the JRE 1.4 environment.

Thanks

Upvotes: 2

Views: 696

Answers (5)

Rogério
Rogério

Reputation: 16380

Why not simply use Java 5 for test code only? With a decent IDE, you should be able to have separate modules/projects for test code (Java 5+) and production code (Java 1.4).

Upvotes: 2

JoaoHornburg
JoaoHornburg

Reputation: 907

Besides Zsolt's solution (creating a wrapper), another possible one is extracting the call to a method, and then testing against a subclass which overrides that method.

Code to be tested:

class A{
    protected long now(){
        return System.currentTimeMillis();
    }
}

Unit test:

class ATest{
    public void testStuff(){
        // actual test
    }

    class MyA extends A {
        long currentTime;

        protected long now(){
            return currentTime;
        }
    }
}

I prefer the wrapper approach, but subclassing might be useful in some cases.

Upvotes: 1

Tobias
Tobias

Reputation: 7380

Or use a special class for all time-related methods, like DateHelper Then you can mock this in your UnitTests and change the time via a static variable.

Upvotes: 0

Uwe
Uwe

Reputation: 436

easymock doesn't require annotations, so it will work with 1.4.

Upvotes: 0

Zsolt
Zsolt

Reputation: 1484

I suggest to use a wrapper when you deal with static methods. For example in your case, you could use a TimeWrapper:

public class TimeWrapper() {
    public long getCurrentTimeInMillis() {
        return System.currentTimeMillis();
    }
}

Inject the TimeWrapper, when you must get the current time in your other classes. This solution doesn't depend on mocking frameworks and jdks.

Upvotes: 0

Related Questions