java:如何模拟 Calendar.getInstance()? [英] java: how to mock Calendar.getInstance()?
问题描述
在我的代码中,我有这样的东西:
In my code I have something like this:
private void doSomething() {
Calendar today = Calendar.getInstance();
....
}
如何在我的 junit 测试中模拟"它以返回特定日期?
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:
在您当天设置的任何方法/类中注入
Calendar
实例.
private void method(final Calendar cal){今天的日期 = cal.getTime();}
使用 JodaTime 而不是 Calendar
.这不是一个选项,而是一个建议案例,因为 JodaTime 将使您的生活更轻松.这次您仍然需要将其注入到方法中.
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();
日期 jdkDate = dt.toDate();
将 Calendar
包裹在一些允许您获取时间的界面中.然后你只需模拟该接口并让它返回一个常量 Date
.
Wrap Calendar
inside some interface that allows you to fetch the time. You then just mock that interface and get it to return a constant Date
.
今天的日期 = calendarInterfaceInstance.getCurrentDate()
这篇关于java:如何模拟 Calendar.getInstance()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!