【问题标题】:How to mock java Calendar using PowerMockito如何使用 PowerMockito 模拟 Java 日历
【发布时间】:2020-09-03 02:58:46
【问题描述】:

我想通过使用 powermockito 来模拟以下方法以返回 true。

private boolean isResetPswrdLinkExpired(Timestamp timestamp) {

        Calendar then = Calendar.getInstance();
        then.setTime(timestamp);
        then.getTime();
        Calendar now = Calendar.getInstance();
        Long diff = now.getTimeInMillis() - then.getTimeInMillis();
        if (diff < 24 * 60 * 60 * 1000) {
            return false;
        } else {
            return true;
        }
    }

【问题讨论】:

    标签: java junit mockito powermock powermockito


    【解决方案1】:

    不要使用Calendar,而是使用java.time(总是,不仅仅是专门为此;看看该方法的可读性如何)。使用java.time,您可以使用Clock 进行测试。

    class PasswordManager
    
        @Setter
        private Clock clock = Clock.systemUTC();
    
        private boolean isExpired(Instant timestamp) {
            return timestamp.plus(1, DAYS).isBefore(Instant.now(clock));
        }
    

    那么在你的测试用例中,

    passwordManager.setClock(Clock.fixed(...));
    

    (注意:也要避免if(...) { return true } else { return false} 或相反的情况。相反,只需按照我的说明和return !(diff &lt; ...) 直接操作。)

    【讨论】:

      猜你喜欢
      • 2020-10-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多