Skip to content

Tag: LocalTime

Unit test time based logic

A standard unit testing problem is how to unit test code that has a dependency on dates or times. For example a method that returns a greeting according to the time of day:

public String timeOfDayGreeting() {
    LocalTime now = LocalTime.now();
    if (now.isBefore(LocalTime.NOON)) {
        return "Good morning";
    } else if (now.isBefore(LocalTime.of(18, 00))) {
        return "Good afternoon";
    } else {
        return "Good evening";
    }
}

If we were to call this method from a test fixture (say JUnit), it would return different values depending on when the test was run. This is not ideal. Unit tests should pass or fail consistently.

Here’s a simple solution for testing time based code.