Skip to content

Tag: mock

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.

Test System.out with JUnit

Edit: see also the follow up article on how to Test log4j with JUnit if you’re interested in specifically testing log output.

Just occasionally, it can be useful to verify output to System.out in a unit test. For example, if you’re testing application logging or if you’re using log output to sense some other behaviour. It can be tricky to properly mock behaviour of System.out but fortunately, it is possible to test System.out with JUnit.