英文:
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 < 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 < ...)。)
英文:
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 < ...) directly.)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论