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, 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.
- Since:
- 1.3.4
- See Also:
-
Field Summary
FieldsModifier and TypeFieldDescriptionstatic final TimeService
TimeService
implementation based onSystem
. -
Method Summary
-
Field Details
-
SYSTEM
TimeService
implementation based onSystem
.- Since:
- 1.3.4
- See Also:
-
-
Method Details