@Deprecated @FunctionalInterface public interface TimeService
Why using a service interface instead of JVM provided time methods?
Simply because you gain better control over the time understood by the application. For example, if you would have to code an expiration time logic, you would check periodically if the computed expiration timestamp is greater than the now timestamp. So far, so good.
When it comes to testing, things gets worst: you typically have to use
Thread.sleep(long)
to wait for a given amount of time so that your
expiration date is reached. That makes tests much longer to execute and
somehow brittle when you're testing short timeouts.
Using a TimeService
helps you to keep your code readable and provides
a way to better control how the time is flowing for your application
(especially useful in the tests).
For example, TimeService.now()
is used in place of
System.currentTimeMillis()
. in your code and you can easily mock it
and make it return controlled values. Here is an example with Mockito:
@Mock private TimeService time; @BeforeMethod public void setUp() throws Exception { MockitoAnnotations.initMocks(this); } @Test public shouldAdvanceInTime() throws Exception { // Mimics steps in the future at each call when(time.now()).thenReturn(0L, 1000L, 10000L); assertThat(time.now()).isEqualTo(0L); assertThat(time.now()).isEqualTo(1000L); assertThat(time.now()).isEqualTo(10000L); }TimeService provides a default service implementation using the System provided time methods for ease of use.
System.currentTimeMillis()
Modifier and Type | Field and Description |
---|---|
static TimeService |
SYSTEM
Deprecated.
TimeService implementation based on System . |
Modifier and Type | Method and Description |
---|---|
long |
now()
Deprecated.
Returns a value that represents "now" since the epoch.
|
default long |
since(long past)
Deprecated.
Computes the elapsed time between now and
past . |
static final TimeService SYSTEM
TimeService
implementation based on System
.System.currentTimeMillis()
long now()
default long since(long past)
past
.past
- time value to compare to now.Copyright © 2010-2018, ForgeRock All Rights Reserved.