如何使用PowerMockito模拟Java Calendar

huangapple go评论83阅读模式
英文:

How to mock java Calendar using PowerMockito

问题

我想使用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;
    }
}
英文:

I want to mock the following method in a way to return true by using powermockito.

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 &lt; 24 * 60 * 60 * 1000) {
            return false;
        } else {
            return true;
        }
    }

答案1

得分: 2

不要使用 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; ...)。)

英文:

Don't use Calendar, use java.time instead (always, not just specifically for this; see how much more readable the method is). With java.time, you can use Clock for testing.

class PasswordManager

    @Setter
    private Clock clock = Clock.systemUTC();

    private boolean isExpired(Instant timestamp) {
        return timestamp.plus(1, DAYS).isBefore(Instant.now(clock));
    }

Then in your test case,

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

(Note: Also avoid if(...) { return true } else { return false} or the inverse. Instead, just do as I showed and return !(diff &lt; ...) directly.)

huangapple
  • 本文由 发表于 2020年9月3日 10:58:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/63716145.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定