开发者

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开发者_JAVA技巧 with +/- a day/month/year.

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

Thanks


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).


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.


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.


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜