java:如何模拟Calendar.getInstance()? [英] java: how to mock Calendar.getInstance()?

查看:687
本文介绍了java:如何模拟Calendar.getInstance()?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的代码中,我有这样的:

  private void doSomething(){
Calendar today = Calendar .getInstance();
....
}

如何我的junit测试返回一个特定的日期?

解决方案

就我看来,你有三个明智的选择:


  1. 在您设置当天的任何方法/类中注入日历 / p>

    私人无效方法(final calendar cal)
    {
    今天的日期= cal.getTime
    }


  2. 使用 JodaTime 而不是日历。这不是一个选项,更多的一个建议的情况下,JodaTime将使你的生活更容易。



    DateTime dt = new DateTime();



    日期jdkDate = dt.toDate();


  3. 在某个界面中包装日历,允许您获取时间。然后你只是模拟该接口并让它返回一个常数 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:

  1. Inject the Calendar instance in whatever method/class you set that day in.

    private void method(final Calendar cal) { Date today = cal.getTime(); }

  2. 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();

  3. 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.

    Date today = calendarInterfaceInstance.getCurrentDate()

这篇关于java:如何模拟Calendar.getInstance()?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆