Search code examples
javajunitmockitopowermockpowermockito

How to mock java Calendar using PowerMockito


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;
        }
    }

Solution

  • 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.)