如何使用 PowerMockito 模拟 java 日历
How to mock java Calendar using PowerMockito
我想通过使用 powermockito 以 return 真实的方式模拟以下方法。
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;
}
}
不要使用 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 < ...)
即可。)
我想通过使用 powermockito 以 return 真实的方式模拟以下方法。
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;
}
}
不要使用 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 < ...)
即可。)