开发者

How to override the current system date within junits

开发者 https://www.devze.com 2023-01-28 21:05 出处:网络
I want to get curent system d开发者_Go百科ate overriden into my Junits.Please help.One technique I use is to NOT call the usual Date/Calendar factory methods/constructors, nor System.getCurrentTimeMil

I want to get curent system d开发者_Go百科ate overriden into my Junits.Please help.


One technique I use is to NOT call the usual Date/Calendar factory methods/constructors, nor System.getCurrentTimeMillis. Instead I inject a date/time "factory," namely an interface with methods for whatever I need in the way of getting the system time.

Then during test I inject an instance which I control directly (hard-coding the time, or even storing it in a file, depending on what I'm testing). Otherwise I inject an implementation which makes the appropriate real calls to the system.

It's not as much work as it sounds, and makes testing time/date-sensitive code fairly straightforward.


Not really an answer, but maybe your code should be changed so rather than you having to hack up the date object you just pass in the date as an argument, that way you can just pass in whatever you want to unit test that method/code.

Another option would be to make a date interface of some kind then mock that out to return whatever you want, mockito may be able to let you make a dummy date object if its not final and you could then get that to return whatever you want.


You coud use Powermock which allows mocking of static and final methods.


I am not sure of how are you getting your system date, but just an idea: Have you tried to use Mocks (EasyMock/Mockito)?


If you use Joda time, then you can override the time used when constructing DateTime and other classes. In effect, you are using Joda as your factory for date and time objects.

Using Joda is much preferred to using the poorly-designed JDK Calendar class.

0

精彩评论

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

关注公众号