使用 JRE 1.4 模拟当前时间
我目前仅限于使用 JRE 1.4(java 运行时环境),并且我有一个具有一些当前时间计算的类。我正在尝试对该类进行单元测试,但这似乎相当困难,因为我遇到的所有模拟工具都需要 JRE1.4 不支持的注释。
我尝试过使用 JRE 1.4 友好版本的mockito,但这不允许我模拟静态类。 Jmockit 有一个超级简单的解决方案可供下载,但似乎没有 Jmockit 的 JRE1.4 友好版本
如果我使用 JRE1.5 及更高版本,我可以通过两种方法来解决这个问题(模拟出该方法要求当前时间或只是模拟当前系统时间),但遗憾的是我不是。
唯一的解决方案是将当前系统时间传递到具有 +/- 天/月/年的方法中。
不过,如果可能的话,我想在 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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
为什么不简单地使用 Java 5 仅用于测试代码呢?有了一个像样的 IDE,您应该能够为测试代码 (Java 5+) 和生产代码 (Java 1.4) 提供单独的模块/项目。
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).
除了 Zsolt 的解决方案(创建包装器)之外,另一种可能的解决方案是提取对方法的调用,然后针对重写该方法的子类进行测试。
要测试的代码:
单元测试:
我更喜欢包装器方法,但子类化在某些情况下可能很有用。
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:
Unit test:
I prefer the wrapper approach, but subclassing might be useful in some cases.
我建议在处理静态方法时使用包装器。例如,在您的情况下,您可以使用 TimeWrapper:
当您必须在其他类中获取当前时间时,注入 TimeWrapper。该解决方案不依赖于模拟框架和jdks。
I suggest to use a wrapper when you deal with static methods. For example in your case, you could use a TimeWrapper:
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 不需要注释,因此它适用于 1.4。
easymock doesn't require annotations, so it will work with 1.4.
或者对所有与时间相关的方法使用特殊的类,例如 DateHelper
然后您可以在单元测试中模拟它并通过静态变量更改时间。
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.