├── .github ├── dependabot.yml └── workflows │ └── main.yml ├── .gitignore ├── .mvn └── .gitkeep ├── LICENSE ├── README.md ├── pom.xml └── src ├── main └── java │ └── it │ └── mulders │ └── clocky │ ├── AdvanceableTime.java │ └── ManualClock.java └── test └── java └── it └── mulders └── clocky ├── AdvanceableTimeTest.java ├── ManualClockTest.java └── TestUtils.java /.github/dependabot.yml: -------------------------------------------------------------------------------- 1 | version: 2 2 | updates: 3 | - package-ecosystem: maven 4 | directory: "/" 5 | schedule: 6 | interval: monthly 7 | time: "04:00" 8 | open-pull-requests-limit: 10 9 | - package-ecosystem: github-actions 10 | directory: "/" 11 | schedule: 12 | interval: monthly 13 | open-pull-requests-limit: 10 -------------------------------------------------------------------------------- /.github/workflows/main.yml: -------------------------------------------------------------------------------- 1 | name: Run tests 2 | 3 | on: 4 | push: 5 | branches: [ main ] 6 | pull_request: 7 | branches: [ main ] 8 | types: [opened, synchronize, reopened] 9 | 10 | jobs: 11 | build: 12 | strategy: 13 | matrix: 14 | os: [ubuntu-latest, windows-latest, macOS-latest] 15 | java: [11, 17, 21] 16 | fail-fast: false 17 | 18 | runs-on: ${{ matrix.os }} 19 | 20 | steps: 21 | - name: Checkout code 22 | uses: actions/checkout@v4.2.2 23 | 24 | - name: Set up JDK 25 | uses: actions/setup-java@v4.7.1 26 | with: 27 | java-version: ${{ matrix.java }} 28 | distribution: 'adopt' 29 | 30 | - name: Set up cache for ~./m2/repository 31 | uses: actions/cache@v4.2.3 32 | with: 33 | path: ~/.m2/repository 34 | key: clocky-${{ matrix.os }}-java${{ matrix.java }}-${{ hashFiles('**/pom.xml') }} 35 | restore-keys: | 36 | clocky-${{ matrix.os }}-clocky-{{ matrix.java }} 37 | clocky-${{ matrix.os }} 38 | 39 | - name: Build and test code 40 | run: mvn verify 41 | 42 | mutationtesting: 43 | runs-on: ubuntu-latest 44 | 45 | steps: 46 | - uses: actions/checkout@v4.2.2 47 | with: 48 | # Disabling shallow clone is recommended for improving relevancy of reporting 49 | fetch-depth: 0 50 | 51 | - name: Set up cache for ~./m2/repository 52 | uses: actions/cache@v4.2.3 53 | with: 54 | path: ~/.m2/repository 55 | key: clocky-ubuntu-latest-java11-${{ hashFiles('**/pom.xml') }} 56 | 57 | - name: Set up JDK 58 | uses: actions/setup-java@v4.7.1 59 | with: 60 | java-version: 11 61 | distribution: 'adopt' 62 | 63 | - name: Run Pitest 64 | run: mvn test-compile org.pitest:pitest-maven:mutationCoverage 65 | env: 66 | STRYKER_DASHBOARD_API_KEY: ${{ secrets.STRYKER_DASHBOARD_TOKEN }} 67 | 68 | sonarcloud: 69 | runs-on: ubuntu-latest 70 | 71 | steps: 72 | - uses: actions/checkout@v4.2.2 73 | with: 74 | # Disabling shallow clone is recommended for improving relevancy of reporting 75 | fetch-depth: 0 76 | 77 | - name: Set up cache for ~./m2/repository 78 | uses: actions/cache@v4.2.3 79 | with: 80 | path: ~/.m2/repository 81 | key: clocky-ubuntu-latest-java11-${{ hashFiles('**/pom.xml') }} 82 | 83 | - name: Set up JDK 84 | uses: actions/setup-java@v4.7.1 85 | with: 86 | java-version: 17 87 | distribution: 'adopt' 88 | 89 | - name: SonarCloud Scan 90 | run: mvn -P sonarcloud -Dsonar.login=$SONAR_TOKEN verify sonar:sonar 91 | env: 92 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }} 93 | SONAR_TOKEN: ${{ secrets.SONAR_TOKEN }} -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Directories 2 | target/ 3 | .idea/ 4 | 5 | # Files 6 | *.iml -------------------------------------------------------------------------------- /.mvn/.gitkeep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mthmulders/clocky/1fd53a22b6e35cb698a6ad1558a2a2a10442778c/.mvn/.gitkeep -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # 🕰️ Clocky 2 | [![Run tests](https://github.com/mthmulders/clocky/workflows/Run%20tests/badge.svg)](https://github.com/mthmulders/clocky/actions/workflows/main.yml?query=branch%3Amain) 3 | [![SonarCloud quality gate](https://sonarcloud.io/api/project_badges/measure?project=mthmulders_clocky&metric=alert_status)](https://sonarcloud.io/dashboard?id=mthmulders_clocky) 4 | [![SonarCloud vulnerability count](https://sonarcloud.io/api/project_badges/measure?project=mthmulders_clocky&metric=vulnerabilities)](https://sonarcloud.io/dashboard?id=mthmulders_clocky) 5 | [![SonarCloud technical debt](https://sonarcloud.io/api/project_badges/measure?project=mthmulders_clocky&metric=sqale_index)](https://sonarcloud.io/dashboard?id=mthmulders_clocky) 6 | [![Dependabot Status](https://api.dependabot.com/badges/status?host=github&repo=mthmulders/clocky)](https://dependabot.com) 7 | [![Mutation testing badge](https://img.shields.io/endpoint?style=plastic&url=https%3A%2F%2Fbadge-api.stryker-mutator.io%2Fgithub.com%2Fmthmulders%2Fclocky%2Fmain)](https://dashboard.stryker-mutator.io/reports/github.com/mthmulders/clocky/main) 8 | [![Maven Central](https://img.shields.io/maven-central/v/it.mulders.clocky/clocky.svg?color=brightgreen&label=Maven%20Central)](https://search.maven.org/artifact/it.mulders.clocky/clocky) 9 | 10 | ## 🚀 TL;DR 11 | Clocky is a test stub for the [`java.time.Clock` class](https://docs.oracle.com/javase/8/docs/api/index.html?java/time/Clock.html) introduced with JSR-310 in Java 8. 12 | It lets you control how time flies in your tests. 13 | 14 | ## 📖 The longer story 15 | Starting with Java 8, Java has a new class: [`java.time.Clock`](https://docs.oracle.com/javase/8/docs/api/index.html?java/time/Clock.html). 16 | This class provides access to the current instant, date and time using a time-zone. 17 | 18 | Previously, Java programmers would use [`System.currentTimeInMillis`](https://docs.oracle.com/javase/8/docs/api/java/lang/System.html#currentTimeMillis--). 19 | Since that is a static method, it's hard to replace it with a stub for testing purposes. 20 | 21 | The `Clock` class solves this by providing an instance method, [`millis`](https://docs.oracle.com/javase/8/docs/api/java/time/Clock.html#millis--). 22 | It is equivalent - and in fact delegates to - calling `System.currentTimeInMillis`. 23 | Apart from `millis()`, the `Clock` class provides other valuable methods such as [`instant()`](https://docs.oracle.com/javase/8/docs/api/java/time/Clock.html#instant--) which returns the same value, wrapped in an instance of [`Instant`](https://docs.oracle.com/javase/8/docs/api/index.html?java/time/Instant.html). 24 | 25 | Since `millis()` and `instant()` are both instance methods of the `Clock` class, it becomes easier to replace those calls with a test stub. 26 | 27 | ### 📦️ Default implementations 28 | The `Clock` class is an abstract class, and Java ships with a few implementations: 29 | 30 | * `SystemClock`, returned by [`Clock.system()`](https://docs.oracle.com/javase/8/docs/api/java/time/Clock.html#system-java.time.ZoneId-), [`Clock.systemDefaultZone()`](https://docs.oracle.com/javase/8/docs/api/java/time/Clock.html#systemDefaultZone--) and [`Clock.systemUTC()`](https://docs.oracle.com/javase/8/docs/api/java/time/Clock.html#systemUTC--). 31 | This clock returns the current instant using best available system clock, usually by calling `System.currentTimeInMillis`. 32 | This is the type that you would typically use in your application. 33 | * `FixedClock`, returned by [`Clock.fixed()`](https://docs.oracle.com/javase/8/docs/api/java/time/Clock.html#fixed-java.time.Instant-java.time.ZoneId-). 34 | As the name suggests, this clock always returns the same instant. 35 | * `OffsetClock`, returned by [`Clock.offset()`](https://docs.oracle.com/javase/8/docs/api/java/time/Clock.html#offset-java.time.Clock-java.time.Duration-). 36 | This clock adds an offset to an underlying clock - which is why you need a second clock to act as the "base" time. 37 | * `TickClock`, returned by [`Clock.tick()`](https://docs.oracle.com/javase/8/docs/api/java/time/Clock.html#tick-java.time.Clock-java.time.Duration-), [`Clock.tickMinutes()`](https://docs.oracle.com/javase/8/docs/api/java/time/Clock.html#tickMinutes-java.time.ZoneId-) and [`Clock.tickSeconds()`](https://docs.oracle.com/javase/8/docs/api/java/time/Clock.html#tickSeconds-java.time.ZoneId-). 38 | This clock returns instants from the specified clock truncated to the nearest occurrence of the specified duration. 39 | 40 | ### 🧪 Testing 41 | 42 | When it comes to testing, often it doesn't matter what the exact time is during a test. 43 | But there are cases when it matters a lot. 44 | Let's say you have code that measures how long a method invocation takes - useful for monitoring purposes. 45 | 46 | ```java 47 | final long start = System.currentTimeInMillis(); 48 | // ... actual method invocation 49 | final long end = System.currentTimeInMillis(); 50 | final long duration = end - start; 51 | ``` 52 | 53 | In such a case, you want to control **exactly** how much time passes between the two invocations of `System.currentTimeInMillis`. 54 | 55 | If we add an instance variable of type `Clock`, and make sure to provide for an implementation, we could rewrite that code: 56 | 57 | ```java 58 | final Instant start = clock.instant(); 59 | // ... actual method invocation 60 | final Instant end = clock.instant(); 61 | final Duration duration = Duration.between(start, end); 62 | ``` 63 | 64 | It's clear to see that this code is way easier to test than the previous version. 65 | Unfortunately, the default implementations of `Clock` do not include a version that is suitable for this scenario. 66 | 67 | * A _Fixed Clock_ doesn't progress, so it's unsuitable. 68 | * The _System Clock_ does progress, but it's not controllable. This means you cannot predict the value of `duration`. 69 | * The _Offset Clock_ and the _Tick Clock_ are both based on another clock, so they need either of the above, which are both unsuitable. 70 | 71 | **This is where Clocky 🕰️ comes in.** 72 | 73 | Clocky gives you a `Clock` that you control very precisely from your tests. 74 | 75 | ```java 76 | final long base = System.currentTimeMillis(); // could be any value 77 | final AtomicReference instant = new AtomicReference<>(); 78 | final Clock clock = new ManualClock(instant::get); 79 | 80 | // create system under test, passing clock along. 81 | 82 | // invoke system under test 83 | instant.set(Instant.ofEpochMilli(base)); 84 | // invoke system under test 85 | instant.set(Instant.ofEpochMilli(base + 10)); 86 | // invoke system under test 87 | 88 | // verify system under test to see the duration is indeed 10 millis 89 | ``` 90 | 91 | Additionally, Clocky provides the `AdvanceableTime` utility for incrementally controlling time in your tests. 92 | This also guarantees that time is always incremental, since not just any `Instant` can be provided. 93 | 94 | ```java 95 | final AdvanceableTime time = new AdvanceableTime(Instant.EPOCH); // can start at any Instant 96 | final Clock clock = new ManualClock(time); 97 | 98 | // create system under test, passing clock along. 99 | 100 | // invoke system under test 101 | time.advanceBy(Duration.ofMillis(10)); 102 | // invoke system under test 103 | 104 | // verify system under test to see the duration is indeed 10 millis 105 | ``` 106 | 107 | ## ⚖️ License 108 | Clocky is licensed under the Apache License, version 2. 109 | See [**LICENSE**](./LICENSE) for the full text of the license. 110 | 111 | ## 🛠️ Contributing 112 | Do you have an idea for Clocky, or want to report a bug? 113 | All contributions are welcome! 114 | Feel free to [file an issue](https://github.com/mthmulders/clocky/issues/new) with your idea, question or whatever it is you want to contribute. 115 | -------------------------------------------------------------------------------- /pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4.0.0 4 | 5 | it.mulders.clocky 6 | clocky 7 | 0.4.4-SNAPSHOT 8 | 9 | Clocky 10 | https://github.com/mthmulders/clocky 11 | Time-related test utilities for Java 12 | 13 | 14 | UTF-8 15 | 1.8 16 | 1.8 17 | 18 | 3.27.3 19 | 5.12.2 20 | 21 | 22 | 23 | 24 | Apache License, Version 2.0 25 | https://www.apache.org/licenses/LICENSE-2.0 26 | 27 | 28 | 29 | 30 | 31 | mthmulders 32 | Maarten Mulders 33 | Europe/Amsterdam 34 | https://maarten.mulders.it/ 35 | 36 | 37 | 38 | 39 | https://github.com/mthmulders/clocky 40 | scm:git:https://github.com/mthmulders/clocky.git 41 | scm:git:git@github.com:mthmulders/clocky.git 42 | HEAD 43 | 44 | 45 | 46 | GitHub 47 | https://github.com/mthmulders/clocky/issues 48 | 49 | 50 | 51 | 52 | org.junit.jupiter 53 | junit-jupiter 54 | test 55 | 56 | 57 | org.assertj 58 | assertj-core 59 | 60 | 61 | nl.jqno.equalsverifier 62 | equalsverifier 63 | 64 | 65 | net.bytebuddy 66 | byte-buddy 67 | 68 | 69 | 70 | 71 | 72 | 73 | 74 | 75 | org.junit 76 | junit-bom 77 | ${junit.jupiter.version} 78 | pom 79 | import 80 | 81 | 82 | 83 | org.assertj 84 | assertj-core 85 | ${assertj.version} 86 | test 87 | 88 | 89 | 90 | nl.jqno.equalsverifier 91 | equalsverifier 92 | 3.19.4 93 | test 94 | 95 | 96 | 97 | 98 | 99 | 100 | 101 | org.apache.maven.plugins 102 | maven-enforcer-plugin 103 | 104 | 105 | org.apache.maven.plugins 106 | maven-jar-plugin 107 | 108 | 109 | 110 | it.mulders.clocky 111 | 112 | 113 | 114 | 115 | 116 | org.sonatype.central 117 | central-publishing-maven-plugin 118 | 119 | 120 | 121 | 122 | 123 | org.apache.maven.plugins 124 | maven-clean-plugin 125 | 3.4.1 126 | 127 | 128 | org.apache.maven.plugins 129 | maven-resources-plugin 130 | 3.3.1 131 | 132 | 133 | org.apache.maven.plugins 134 | maven-compiler-plugin 135 | 3.14.0 136 | 137 | 138 | org.apache.maven.plugins 139 | maven-surefire-plugin 140 | 3.5.3 141 | 142 | 143 | org.apache.maven.plugins 144 | maven-jar-plugin 145 | 3.4.2 146 | 147 | 148 | org.apache.maven.plugins 149 | maven-install-plugin 150 | 3.1.4 151 | 152 | 153 | org.apache.maven.plugins 154 | maven-deploy-plugin 155 | 3.1.4 156 | 157 | true 158 | 159 | 160 | 161 | org.apache.maven.plugins 162 | maven-site-plugin 163 | 3.21.0 164 | 165 | 166 | org.apache.maven.plugins 167 | maven-source-plugin 168 | 3.3.1 169 | 170 | 171 | org.apache.maven.plugins 172 | maven-javadoc-plugin 173 | 3.11.2 174 | 175 | 176 | org.apache.maven.plugins 177 | maven-release-plugin 178 | 3.1.1 179 | 180 | release 181 | v@{project.version} 182 | 183 | 184 | 185 | org.apache.maven.plugins 186 | maven-project-info-reports-plugin 187 | 3.9.0 188 | 189 | 190 | org.sonarsource.scanner.maven 191 | sonar-maven-plugin 192 | 5.1.0.4751 193 | 194 | 195 | org.jacoco 196 | jacoco-maven-plugin 197 | 0.8.13 198 | 199 | 200 | org.pitest 201 | pitest-maven 202 | 1.19.1 203 | 204 | 205 | it.mulders.stryker 206 | pit-dashboard-reporter 207 | 0.3.3 208 | 209 | 210 | org.pitest 211 | pitest-junit5-plugin 212 | 1.2.2 213 | 214 | 215 | io.github.wmaarts 216 | pitest-mutation-testing-elements-plugin 217 | 0.6.3 218 | 219 | 220 | 221 | 222 | stryker-dashboard 223 | 224 | false 225 | 226 | 227 | 228 | org.apache.maven.plugins 229 | maven-enforcer-plugin 230 | 3.5.0 231 | 232 | 233 | org.codehaus.mojo 234 | extra-enforcer-rules 235 | 1.10.0 236 | 237 | 238 | org.sonatype.ossindex.maven 239 | ossindex-maven-enforcer-rules 240 | 3.2.0 241 | 242 | 243 | 244 | 245 | enforce-rules 246 | 247 | enforce 248 | 249 | 250 | true 251 | 252 | 254 | 255 | 256 | 258 | 259 | 260 | runtime 261 | 262 | 263 | 264 | 266 | 267 | runtime 268 | 269 | 270 | 271 | 272 | 273 | 275 | 276 | ${maven.compiler.source} 277 | 278 | 279 | 280 | 281 | ${maven.compiler.source} 282 | 283 | 284 | 285 | 286 | 3.5.0 287 | 288 | 289 | 290 | 291 | 292 | 293 | 294 | org.apache.maven.plugins 295 | maven-gpg-plugin 296 | 3.2.7 297 | 298 | 299 | org.sonatype.central 300 | central-publishing-maven-plugin 301 | 0.7.0 302 | true 303 | 304 | true 305 | ${project.name} ${project.version} 306 | sonatype-central-portal 307 | 308 | 309 | 310 | 311 | 312 | 313 | 314 | 315 | ossrh 316 | https://oss.sonatype.org/content/repositories/snapshots 317 | 318 | 319 | ossrh 320 | https://oss.sonatype.org/service/local/staging/deploy/maven2/ 321 | 322 | 323 | 324 | 325 | 326 | coverage 327 | 328 | 329 | java-16 330 | 331 | 16 332 | 333 | 334 | -Dnet.bytebuddy.experimental=true 335 | 336 | 337 | 338 | release 339 | 340 | 341 | 342 | org.apache.maven.plugins 343 | maven-gpg-plugin 344 | 345 | 346 | sign-artifacts 347 | verify 348 | 349 | sign 350 | 351 | 352 | 353 | 354 | 355 | org.apache.maven.plugins 356 | maven-source-plugin 357 | 358 | 359 | attach-sources 360 | 361 | jar-no-fork 362 | 363 | 364 | 365 | 366 | 367 | org.apache.maven.plugins 368 | maven-javadoc-plugin 369 | 370 | 371 | attach-javadocs 372 | 373 | jar 374 | 375 | 376 | 377 | 378 | 379 | 380 | 381 | 382 | sonarcloud 383 | 384 | mthmulders_clocky 385 | mthmulders-github 386 | https://sonarcloud.io 387 | 388 | 389 | 390 | 391 | org.jacoco 392 | jacoco-maven-plugin 393 | 394 | 395 | prepare-agent 396 | 397 | prepare-agent 398 | 399 | 400 | 401 | prepare-agent-integration 402 | 403 | prepare-agent-integration 404 | 405 | 406 | 407 | report 408 | 409 | report 410 | 411 | 412 | 413 | report-integration 414 | 415 | report-integration 416 | 417 | 418 | 419 | 420 | 421 | 422 | 423 | 424 | 425 | -------------------------------------------------------------------------------- /src/main/java/it/mulders/clocky/AdvanceableTime.java: -------------------------------------------------------------------------------- 1 | package it.mulders.clocky; 2 | 3 | import java.time.Clock; 4 | import java.time.Duration; 5 | import java.time.Instant; 6 | import java.time.ZoneId; 7 | import java.util.Objects; 8 | 9 | /** 10 | * Container to control time. Intended to be used in conjunction with {@link ManualClock}. 11 | * This class satisfies the assumption that time is strictly increasing. 12 | */ 13 | public final class AdvanceableTime { 14 | private Instant instant; 15 | 16 | /** 17 | * Creates an instance that initially returns the provided initial instant. 18 | * @param initialInstant the initial point in time. 19 | */ 20 | public AdvanceableTime(final Instant initialInstant) { 21 | Objects.requireNonNull(initialInstant, "Initial instant may not be null"); 22 | 23 | this.instant = initialInstant; 24 | } 25 | 26 | /** 27 | * @return the current time. 28 | */ 29 | public Instant instant() { 30 | return instant; 31 | } 32 | 33 | /** 34 | * Manually advances the time by the specified duration. The duration may not be negative. 35 | * @param duration amount of time to advance by. 36 | */ 37 | public synchronized void advanceBy(final Duration duration) { 38 | if (duration.isNegative()) { 39 | throw new IllegalArgumentException("Duration may not be negative"); 40 | } 41 | 42 | instant = instant.plus(duration); 43 | } 44 | 45 | @Override 46 | public final boolean equals(Object other) { 47 | if (other instanceof AdvanceableTime) { 48 | return this.instant.equals(((AdvanceableTime) other).instant); 49 | } 50 | 51 | return false; 52 | } 53 | 54 | @Override 55 | public int hashCode() { 56 | return instant.hashCode(); 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /src/main/java/it/mulders/clocky/ManualClock.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2020 Maarten Mulders 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package it.mulders.clocky; 17 | 18 | import java.time.Clock; 19 | import java.time.Instant; 20 | import java.time.ZoneId; 21 | import java.util.Objects; 22 | import java.util.function.Supplier; 23 | 24 | /** 25 | * A clock that by itself will not progress other than when it is explicitly told to do so. 26 | * This clock will determine the current time by calling the function that is provided at construction. 27 | */ 28 | public final class ManualClock extends Clock { 29 | private final Supplier supplier; 30 | private final ZoneId zoneId; 31 | 32 | /** 33 | * Creates an instance that always returns the instant returned by a factory method. The clock runs in the system's 34 | * default time zone. 35 | * @param advanceableTime the time to return. 36 | */ 37 | public ManualClock(final AdvanceableTime advanceableTime) { 38 | this(advanceableTime, ZoneId.systemDefault()); 39 | } 40 | 41 | /** 42 | * Creates an instance that always returns the instant returned by a factory method. 43 | * @param advanceableTime the time to return. 44 | * @param zoneId the time zone to use to convert the instant to date-time. 45 | */ 46 | public ManualClock(final AdvanceableTime advanceableTime, final ZoneId zoneId) { 47 | this(advanceableTime::instant, zoneId); 48 | } 49 | 50 | /** 51 | * Creates an instance that always returns the instant returned by a factory method. The clock runs in the system's 52 | * default time zone. 53 | * @param instantSupplier the function to be invoked when asked for the current time. 54 | */ 55 | public ManualClock(final Supplier instantSupplier) { 56 | this(instantSupplier, ZoneId.systemDefault()); 57 | } 58 | 59 | /** 60 | * Creates an instance that always returns the instant returned by a factory method. 61 | * @param instantSupplier the function to be invoked when asked for the current time. 62 | * @param zoneId the time zone to use to convert the instant to date-time. 63 | */ 64 | public ManualClock(final Supplier instantSupplier, final ZoneId zoneId) { 65 | Objects.requireNonNull(instantSupplier, "Instant supplier may not be null"); 66 | Objects.requireNonNull(zoneId, "Zone ID may not be null"); 67 | 68 | this.supplier = instantSupplier; 69 | this.zoneId = zoneId; 70 | } 71 | 72 | /** {@inheritDoc} */ 73 | @Override 74 | public ZoneId getZone() { 75 | return zoneId; 76 | } 77 | 78 | /** {@inheritDoc} */ 79 | @Override 80 | public Clock withZone(final ZoneId zoneId) { 81 | if (Objects.equals(this.zoneId, zoneId)) { 82 | return this; 83 | } 84 | 85 | return new ManualClock(supplier, zoneId); 86 | } 87 | 88 | /** {@inheritDoc} */ 89 | @Override 90 | public Instant instant() { 91 | return supplier.get(); 92 | } 93 | 94 | @Override 95 | public final boolean equals(final Object other) { 96 | if (other instanceof ManualClock) { 97 | final ManualClock that = (ManualClock) other; 98 | return this.supplier.equals(that.supplier) && this.zoneId.equals(that.zoneId); 99 | } 100 | return false; 101 | } 102 | 103 | @Override 104 | public final int hashCode() { 105 | return this.supplier.hashCode() ^ this.zoneId.hashCode(); 106 | } 107 | } 108 | -------------------------------------------------------------------------------- /src/test/java/it/mulders/clocky/AdvanceableTimeTest.java: -------------------------------------------------------------------------------- 1 | package it.mulders.clocky; 2 | 3 | import nl.jqno.equalsverifier.EqualsVerifier; 4 | import nl.jqno.equalsverifier.Warning; 5 | import org.assertj.core.api.WithAssertions; 6 | import org.junit.jupiter.api.Test; 7 | 8 | import java.time.Duration; 9 | import java.time.Instant; 10 | import java.time.temporal.ChronoUnit; 11 | 12 | class AdvanceableTimeTest implements WithAssertions { 13 | 14 | @Test 15 | void instant_should_return_value_at_construction_time() { 16 | final AdvanceableTime advanceableTime = new AdvanceableTime(Instant.EPOCH); 17 | 18 | assertThat(advanceableTime.instant()).isEqualTo(Instant.EPOCH); 19 | } 20 | 21 | @Test 22 | void allows_manual_progression() throws InterruptedException { 23 | final AdvanceableTime advanceableTime = new AdvanceableTime(Instant.EPOCH); 24 | 25 | assertThat(advanceableTime.instant()).isEqualTo(Instant.EPOCH); 26 | TestUtils.sleep(Duration.ofMillis(10)); 27 | assertThat(advanceableTime.instant()).isEqualTo(Instant.EPOCH); 28 | 29 | advanceableTime.advanceBy(Duration.ofHours(2)); 30 | 31 | assertThat(advanceableTime.instant()).isEqualTo(Instant.EPOCH.plus(2, ChronoUnit.HOURS)); 32 | TestUtils.sleep(Duration.ofMillis(10)); 33 | assertThat(advanceableTime.instant()).isEqualTo(Instant.EPOCH.plus(2, ChronoUnit.HOURS)); 34 | 35 | advanceableTime.advanceBy(Duration.ZERO); 36 | 37 | assertThat(advanceableTime.instant()).isEqualTo(Instant.EPOCH.plus(2, ChronoUnit.HOURS)); 38 | } 39 | 40 | @Test 41 | void disallows_negative_progression() { 42 | final AdvanceableTime advanceableTime = new AdvanceableTime(Instant.EPOCH); 43 | 44 | assertThatThrownBy(() -> advanceableTime.advanceBy(Duration.ofMillis(-1))).isInstanceOf(IllegalArgumentException.class); 45 | } 46 | 47 | @Test 48 | void equals_contract() { 49 | EqualsVerifier.forClass(AdvanceableTime.class) 50 | .withNonnullFields("instant") 51 | .suppress(Warning.NONFINAL_FIELDS) 52 | .verify(); 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /src/test/java/it/mulders/clocky/ManualClockTest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2020 Maarten Mulders 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package it.mulders.clocky; 17 | 18 | import nl.jqno.equalsverifier.EqualsVerifier; 19 | import org.assertj.core.api.WithAssertions; 20 | import org.junit.jupiter.api.Test; 21 | 22 | import java.time.Clock; 23 | import java.time.Duration; 24 | import java.time.Instant; 25 | import java.time.ZoneOffset; 26 | import java.util.concurrent.atomic.AtomicLong; 27 | import java.util.function.Supplier; 28 | 29 | class ManualClockTest implements WithAssertions { 30 | // The Clock javadoc states that instances of Clock must be final, immutable and thread-safe. 31 | 32 | private static final Supplier EPOCH_SUPPLIER = () -> Instant.EPOCH; 33 | 34 | @Test 35 | void instant_should_return_value_at_construction_time() { 36 | final Clock clock = new ManualClock(EPOCH_SUPPLIER); 37 | 38 | assertThat(clock.instant()).isEqualTo(Instant.EPOCH); 39 | } 40 | 41 | @Test 42 | void instant_should_return_advanceablevalue_at_construction_time() { 43 | final AdvanceableTime advanceableTime = new AdvanceableTime(Instant.EPOCH); 44 | final Clock clock = new ManualClock(advanceableTime); 45 | 46 | assertThat(clock.instant()).isEqualTo(Instant.EPOCH); 47 | } 48 | 49 | @Test 50 | void millis_should_return_value_at_construction_time() { 51 | final Clock clock = new ManualClock(EPOCH_SUPPLIER); 52 | 53 | assertThat(clock.millis()).isEqualTo(Instant.EPOCH.toEpochMilli()); 54 | } 55 | 56 | @Test 57 | void millis_should_return_advanceablevalue_at_construction_time() { 58 | final AdvanceableTime advanceableTime = new AdvanceableTime(Instant.EPOCH); 59 | final Clock clock = new ManualClock(advanceableTime); 60 | 61 | assertThat(clock.millis()).isEqualTo(Instant.EPOCH.toEpochMilli()); 62 | } 63 | 64 | @Test 65 | void constructor_should_use_system_default_zone() { 66 | final Clock clock = new ManualClock(EPOCH_SUPPLIER); 67 | 68 | assertThat(clock.getZone()).isEqualTo(ZoneOffset.systemDefault()); 69 | } 70 | 71 | @Test 72 | void advanceabletime_constructor_should_use_system_default_zone() { 73 | final AdvanceableTime advanceableTime = new AdvanceableTime(Instant.EPOCH); 74 | final Clock clock = new ManualClock(advanceableTime); 75 | 76 | assertThat(clock.getZone()).isEqualTo(ZoneOffset.systemDefault()); 77 | } 78 | 79 | @Test 80 | void constructor_should_override_zone() { 81 | final ZoneOffset offset = ZoneOffset.ofHoursMinutes(4, 30); 82 | final Clock clock = new ManualClock(EPOCH_SUPPLIER, offset); 83 | 84 | assertThat(clock.getZone()).isEqualTo(offset); 85 | } 86 | 87 | @Test 88 | void advanceabletime_constructor_should_override_zone() { 89 | final AdvanceableTime advanceableTime = new AdvanceableTime(Instant.EPOCH); 90 | final ZoneOffset offset = ZoneOffset.ofHoursMinutes(4, 30); 91 | final Clock clock = new ManualClock(advanceableTime, offset); 92 | 93 | assertThat(clock.getZone()).isEqualTo(offset); 94 | } 95 | 96 | @Test 97 | void with_same_zone_return_same_clock() { 98 | final Clock clock = new ManualClock(EPOCH_SUPPLIER); 99 | 100 | final Clock newClock = clock.withZone(ZoneOffset.systemDefault()); 101 | 102 | assertThat(newClock).isSameAs(clock); 103 | } 104 | 105 | @Test 106 | void with_other_zone_return_new_clock() { 107 | final ZoneOffset offset = ZoneOffset.ofHoursMinutes(4, 30); 108 | final Clock clock = new ManualClock(EPOCH_SUPPLIER); 109 | 110 | final Clock newClock = clock.withZone(offset); 111 | 112 | assertThat(newClock).isNotSameAs(clock); 113 | assertThat(newClock.getZone()).isEqualTo(offset); 114 | } 115 | 116 | @Test 117 | void allows_manual_progression() throws InterruptedException { 118 | final long initialValue = Instant.now().toEpochMilli(); 119 | final long updatedValue = initialValue + 10_000L; 120 | final AtomicLong instant = new AtomicLong(); 121 | instant.set(initialValue); 122 | 123 | final Clock clock = new ManualClock(() -> Instant.ofEpochMilli(instant.get())); 124 | 125 | assertThat(clock.millis()).isEqualTo(initialValue); 126 | TestUtils.sleep(Duration.ofMillis(10)); 127 | assertThat(clock.millis()).isEqualTo(initialValue); 128 | 129 | instant.set(updatedValue); 130 | 131 | assertThat(clock.millis()).isEqualTo(updatedValue); 132 | TestUtils.sleep(Duration.ofMillis(10)); 133 | assertThat(clock.millis()).isEqualTo(updatedValue); 134 | } 135 | 136 | 137 | @Test 138 | void allows_advanceabletime_progression() throws InterruptedException { 139 | final AdvanceableTime advanceableTime = new AdvanceableTime(Instant.EPOCH); 140 | final Clock clock = new ManualClock(advanceableTime, ZoneOffset.UTC); 141 | 142 | assertThat(clock.millis()).isEqualTo(0L); 143 | 144 | advanceableTime.advanceBy(Duration.ofSeconds(10)); 145 | 146 | assertThat(clock.millis()).isEqualTo(10_000L); 147 | } 148 | 149 | @Test 150 | void equals_contract() { 151 | EqualsVerifier.forClass(ManualClock.class) 152 | .withNonnullFields("supplier", "zoneId") 153 | .withRedefinedSuperclass() 154 | .verify(); 155 | } 156 | } 157 | -------------------------------------------------------------------------------- /src/test/java/it/mulders/clocky/TestUtils.java: -------------------------------------------------------------------------------- 1 | package it.mulders.clocky; 2 | 3 | import java.time.Duration; 4 | 5 | class TestUtils { 6 | private TestUtils() { 7 | } 8 | 9 | @SuppressWarnings({ 10 | "java:S2925" // "Thread.sleep" should not be used in tests 11 | }) 12 | static void sleep(Duration duration) throws InterruptedException { 13 | Thread.sleep(duration.toMillis()); 14 | } 15 | } 16 | --------------------------------------------------------------------------------