Video in progress

Strong Junior 🧪 Testing

If the code calls LocalDateTime.now() inside, how do you reliably test time-dependent logic?

Instead of getting the time directly, you pass java.time.Clock in as a dependency: Clock.systemDefaultZone() in prod and Clock.fixed(...) in the test. That way the test gives the same result for any date and time.

📖 Answer

The problematic code:

boolean isExpired(Subscription s) {
    return s.endsAt().isBefore(LocalDateTime.now());   // the test passes today, fails tomorrow
}

The fixed version:

@Service
class SubscriptionService {
    private final Clock clock;
    SubscriptionService(Clock clock) { this.clock = clock; }

    boolean isExpired(Subscription s) {
        return s.endsAt().isBefore(LocalDateTime.now(clock));
    }
}

// in the configuration
@Bean Clock clock() { return Clock.system(ZoneId.of("Asia/Tashkent")); }

// in the test
var clock = Clock.fixed(Instant.parse("2026-03-01T10:00:00Z"), ZoneOffset.UTC);
var service = new SubscriptionService(clock);

Now you can build exactly the situation "the subscription ended February 28, and today is March 1". Leap years, end of month, the midnight boundary: all of it is tested this way.

You can also do it with Mockito.mockStatic(LocalDateTime.class) (in Mockito 5 the inline mock maker is the default, so a separate mockito-inline isn't needed), but that's the crude way: the code doesn't change, while the test is slow and brittle. The same idea applies to UUID.randomUUID() and random numbers: inject the generator.