lundi 19 octobre 2020

How to change the internal state of a Clock instance in Java?

I have a service that verifies expiration of dates:

@RequiredArgsConstructor
public class ExpirationVerificationService {
  private final Clock clock;

  public boolean hasPassed(Instant instant) {
    return Instant.now(clock).isAfter(instant);
  }
}

I want to verify that hasPassed returns different values as time passes:

public class ExpirationVerificationServiceTest {

  private ExpirationVerificationService service;
  private Clock clock;

  @BeforeEach
  public void init() {
    clock = Clock.fixed(Instant.EPOCH, ZoneId.of("UTC"));
    service = new ExpirationVerificationService(clock);
  }

  @Test
  public void testHasExpired() {
    Instant instant = Instant.now(clock).plus(Duration.ofDays(30);
    assertFalse(service.hasPassed(instant));

    // TODO move clock to future
    assertTrue(service.hasPassed(instant));
  }

}

How can I update the internal state of the Clock instance to be in the future?

note: the actual business logic I'm testing is much more complicated than this example (verifying expiration of Oauth tokens coming from a DB), I can't just use a different Instant instance in the past.

Aucun commentaire:

Enregistrer un commentaire