java:如何模拟Calendar.getInstance()? [英] java: how to mock Calendar.getInstance()?
问题描述
在我的代码中,我有这样的:
private void doSomething(){
Calendar today = Calendar .getInstance();
....
}
如何我的junit测试返回一个特定的日期?
就我看来,你有三个明智的选择:
-
在您设置当天的任何方法/类中注入
日历
/ p>
私人无效方法(final calendar cal)
{
今天的日期= cal.getTime
} -
使用 JodaTime 而不是
日历
。这不是一个选项,更多的一个建议的情况下,JodaTime将使你的生活更容易。
DateTime dt = new DateTime();
日期jdkDate = dt.toDate();
-
在某个界面中包装
日历
,允许您获取时间。然后你只是模拟该接口并让它返回一个常数Date
。
日期today = calendarInterfaceInstance.getCurrentDate()
In my code I have something like this:
private void doSomething() {
Calendar today = Calendar.getInstance();
....
}
How can I "mock" it in my junit test to return a specific date?
As far as I see it you have three sensible options:
Inject the
Calendar
instance in whatever method/class you set that day in.private void method(final Calendar cal) { Date today = cal.getTime(); }
Use JodaTime instead of
Calendar
. This is less an option and more a case of a suggestion as JodaTime will make your life a lot easier. You will still need to inject this time in to the method.DateTime dt = new DateTime();
Date jdkDate = dt.toDate();
Wrap
Calendar
inside some interface that allows you to fetch the time. You then just mock that interface and get it to return a constantDate
.Date today = calendarInterfaceInstance.getCurrentDate()
这篇关于java:如何模拟Calendar.getInstance()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!