Is it possible to freeze System.currentTimeMillis() for testing

前端 未结 6 2575
孤街浪徒
孤街浪徒 2021-02-20 02:24

For some testing purposes I would like to predict exactly what System.currentTimeMillis() will return. Is there any way in which I can freeze or manually set what w

6条回答
  •  灰色年华
    2021-02-20 02:47

    I would strongly suggest that you avoid using System.currentTimeMillis (and new Date() etc) in your general code.

    Instead, create a Clock interface representing "a service to give you the current time" and then create one implementation which does use System.currentTimeMillis or whatever, and a fake implementation that you can control explicitly.

    Use dependency injection to make an instance of this service available to code which needs it. In production, use the System.currentTimeMillis version, and in testing use your fake.

    This gives you the ability not just to stop time, but to set it to whatever you want - so you can have static test data which you know will never expire, and you can easily test tricky things around boundaries etc. I've used this approach very successfully in many projects, to the extent that in my Noda Time project it's the way of getting at "the current time".

    Note that if you're doing any serious amount of time work in Java, I'd recommend using Joda Time, and making your Clock interface return an Instant:

    public interface Clock {
        Instant now();
    }
    

提交回复
热议问题