简体   繁体   中英

How to unit test a time dependent method with JUnit

I have the following method which take a UNIX time stamp and returns the age in terms of days, hours, or minutes. I want to unit test it with JUnit but I'm unsure how I would start doing that as the current time is constantly changing. Any advice? Thanks!

Here is the method:

public static String getAge(long unixTime) throws Exception {
        long diff = (System.currentTimeMillis() / 1000) - unixTime;
    diff = diff / 60;
    if (diff < 60) {
        return Math.round(diff) + " m";
    }
    else
        diff /= 60;
    if (diff < 24) {
        return Math.round(diff) + " h";
    }
    else {
        diff /= 24;
        return Math.round(diff) + " d";
    }

}

您应该更改方法的设计以同时接受当前时间和unixTime,或者必须退出纯JUnit并使用PowerMock来模拟System.currentTimeMillis()以返回所需的结果。

I would build a unix timestamp in my unitTest based on the current time. The granularity of the result of the method is coarse enough that a few millisecond difference between when you create the argument and when this method is executed will not be material. Granted, you will need to steer clear of the boundary conditions, ie, a unixTime at 60 minutes and 24 hours.

public void testMinutes() {
    Instant minutesAgo = Instant.ofEpochMilli(System.currentTimeMillis() - 15 * 60 * 1000);
    String result = getAge(minutesAgo.getEpochSecond());
    assertSomething...
}

And so on for hours and days tests.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM