| 1 | # Shared clock |
| 2 | |
| 3 | ## Decision |
| 4 | |
| 5 | A mockable shared `Clock` is used across EDC modules to get the time. |
| 6 | |
| 7 | Other mechanisms for accessing the time, such as calls to `Instant.now()`, `new Date()`, or `System.currentTimeMillis()` shall not be used in production code. They may be used in test code. |
| 8 | |
| 9 | ## Rationale |
| 10 | |
| 11 | This allows writing consistent test code with assertions about time behavior. |
| 12 | |
| 13 | ## Approach |
| 14 | |
| 15 | The shared clock can be injected in service extensions: |
| 16 | |
| 17 | ```java |
| 18 | @Inject |
| 19 | private Clock clock; |
| 20 | ``` |
| 21 | |
| 22 | or with a convenience method: |
| 23 | |
| 24 | ```java |
| 25 | @Override |
| 26 | public void initialize(ServiceExtensionContext context) { |
| 27 | var clock = context.getClock(); |
| 28 | ... |
| 29 | } |
| 30 | ``` |
| 31 | |
| 32 | By default, this provides the system clock. In integration tests, another `Clock` implementation can be registered through mocking: |
| 33 | |
| 34 | ```java |
| 35 | @ExtendWith(EdcExtension.class) |
| 36 | class AnIntegrationTest { |
| 37 | @BeforeEach |
| 38 | void setUp(EdcExtension extension) { |
| 39 | extension.registerServiceMock(Clock.class, Clock.fixed(now, UTC)); |
| 40 | } |
| 41 | } |
| 42 | ``` |
| 43 | |