是否可以更改java中线程或jvm实例的当前时间?
我想测试一些包含依赖于当前运行时间的逻辑的类方法。我想在 JUnit 设置中将线程/jvm/系统时间设置为未来的特定日期并运行我的测试。我也希望这是暂时的。以前有人这样做过吗?
我在想类似于 TimeZone.setDefault(timezone) 的东西
I want to test some class methods that contain logic dependent on the current time it is running. I'd like to set the thread/jvm/system time to a specific future date in the JUnit setup and run my tests. Also I would like this to be temporary. Has anyone done this before?
I was thinking of something similar to TimeZone.setDefault(timezone)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可以使用 AspectJ 并围绕
java.lang.System.currentTimeMillis()
、java.util.Date.new()
和java.util.Calendar 包装方法.getInstance()
根据您的需要调整时间。You could use AspectJ and wrap methods around
java.lang.System.currentTimeMillis()
,java.util.Date.new()
andjava.util.Calendar.getInstance()
which adjust the time according to your needs.我不相信有办法使用 java.util.Date 来做到这一点。
如果您使用的是 joda-time 那么您可以。请参阅此
I don't believe there's a way of doing this using java.util.Date.
If you are using joda-time then you can. See this
我也一直在为此苦苦挣扎。到目前为止,我发现的最好的解决方案是使用一个 TimeHelper 类来管理时间内容:作为日期工厂,保留 DateFormatters 等,以便这些内容不会分布在代码库中。
使用 Easymock 或其他模拟框架,可以轻松测试与时间相关的内容。
I have been struggling with this too. The best solution I found so far is having a TimeHelper class which manages the time stuff : as a Date factory, keeping DateFormatters and so on so that these things are not distributed over the codebase.
With Easymock, or another mock framework, it is then straightforward to test time related stuff.
你的处理方式是错误的。您的类方法应该接受代表时间的
long
值 - 它们不应该接受TimeZone
。如果您重构您的方法,使其与它们从TimeZone
接收“时间”的事实分离,那么您可以轻松测试您的方法,而不必执行您现在尝试执行的操作;您只需使用代表特定时间的预定义long
值调用方法,而不是使用TimeZone
对象调用它们,该对象的默认值是您希望测试的预定值。您需要将从提供该时间值的源接收“时间”参数的方法解耦。通过执行此操作,您可以在使用
TimeZone
或当前系统时间的同时运行代码,并且可以在使用要测试的预定义时间值的同时测试代码。继续尝试重构您的代码,看看您是否能够实现所需的功能 - 您应该能够做到。如有任何其他问题,请回来,我们将很乐意提供帮助!
祝你好运。
You're going about this the wrong way. Your class methods should be accepting a
long
value which represents the time - they should not be accepting aTimeZone
. If you refactor your methods to be decoupled from the fact that they receive there 'time' from aTimeZone
, then you can easily test your methods without having to do what you're trying to do now; you simply call your methods with pre-definedlong
values representative of a particular time, rather then calling them with aTimeZone
object whose default value is something predetermined that you wish to test.You need to decouple the methods which receive a 'time' parameter from the source which provides that time value. By doing this, you can run your code while using
TimeZone
or the current system time, and you can test your code while using predefined time values that you wish to test.Go ahead and try refactoring your code and see if you can achieve the desired capabilities - you should be able to. Come back with any further questions and we'll be glad to help!
Good luck.