Mock Java Date/Time for Testing
Time mocking is a viable solution to avoiding current time inconveniences during testing, which can be accomplished by using the new Java 8 Date/Time API.
Join the DZone community and get the full member experience.
Join For FreeReferencing the current date/time in your source code makes testing pretty difficult. You have to exclude such references from your assertions, which is not a trivial task to complete.
Time mocking is a viable solution to avoiding current time inconveniences during testing, which can be accomplished by using the new Java 8 Date/Time API (JSR 310).
For obtaining the current moment in time all related classes from the java.time
package have the static method now()
.
LocalDate.now();
LocalTime.now();
LocalDateTime.now();
OffsetDateTime.now();
ZonedDateTime.now();
Instant.now();
We will not consider the approach with mocking static methods due to its bad performance reputation.
If you look into the now()
method of any Java API classes you will find that the overridden method works with the system clock:
xxxxxxxxxx
/**
* Obtains the current time from the system clock in the default time-zone.
* <p>
* This will query the {@link Clock#systemDefaultZone() system clock} in the default
* time-zone to obtain the current time.
* <p>
* Using this method will prevent the ability to use an alternate clock for testing
* because the clock is hard-coded.
*
* @return the current time using the system clock and default time-zone, not null
*/
public static LocalTime now() {
return now(Clock.systemDefaultZone());
}
What we can do is create the wrapper class with all the necessary methods for the current time, plus an additional method for mocking time. For the sake of the demo, we will call it Time
:
package com.example.utils;
import java.time.*;
import java.util.TimeZone;
public class Time {
private static Clock CLOCK = Clock.systemDefaultZone();
private static final TimeZone REAL_TIME_ZONE = TimeZone.getDefault();
public static LocalDate currentDate() {
return LocalDate.now(getClock());
}
public static LocalTime currentTime() {
return LocalTime.now(getClock());
}
public static LocalDateTime currentDateTime() {
return LocalDateTime.now(getClock());
}
public static OffsetDateTime currentOffsetDateTime() {
return OffsetDateTime.now(getClock());
}
public static ZonedDateTime currentZonedDateTime() {
return ZonedDateTime.now(getClock());
}
public static Instant currentInstant() {
return Instant.now(getClock());
}
public static long currentTimeMillis() {
return currentInstant().toEpochMilli();
}
public static void useMockTime(LocalDateTime dateTime, ZoneId zoneId) {
Instant instant = dateTime.atZone(zoneId).toInstant();
CLOCK = Clock.fixed(instant, zoneId);
TimeZone.setDefault(TimeZone.getTimeZone(zoneId));
}
public static void useSystemDefaultZoneClock() {
TimeZone.setDefault(REAL_TIME_ZONE);
CLOCK = Clock.systemDefaultZone();
}
private static Clock getClock() {
return CLOCK;
}
}
Let's look into the wrapper class more closely:
- First of all, we remember the system clock and system timezone.
- Using method
userMockTime()
we can override time with the fixed clock and provide the time zone. - Using method
useSystemDefaultZoneClock()
we can reset the clock and the timezone to the system defaults. - All other methods use the provided clock instance.
So far so good, but there are two problems left in this approach:
- The
useMockTime()
method is too dangerous for the production code. What we want is to somehow eliminate the usage of that method in the source code. - We need to enforce using the
Time
class instead of the direct usage of the*Date/Time.now()
methods.
One of the best solutions is the ArchUnit library.
It gives you the opportunity to control your architectural rules using unit tests. Let’s see how we can define our rules using the JUnit 5 engine (there is also an option to define the same rules for the JUnit 4 engine).
We will need to add the necessary dependency (Maven example):
xxxxxxxxxx
<dependency>
<groupId>com.tngtech.archunit</groupId>
<artifactId>archunit-junit5</artifactId>
<version>0.14.1</version>
<scope>test</scope>
</dependency>
And add rule descriptions in the unit test folder:
xxxxxxxxxx
package com.example;
import com.example.utils.OldTimeAdaptor;
import com.example.utils.Time;
import com.tngtech.archunit.core.importer.ImportOption;
import com.tngtech.archunit.junit.AnalyzeClasses;
import com.tngtech.archunit.junit.ArchTest;
import com.tngtech.archunit.lang.ArchRule;
import java.time.*;
import java.util.Date;
import static com.tngtech.archunit.lang.syntax.ArchRuleDefinition.classes;
import static com.tngtech.archunit.lang.syntax.ArchRuleDefinition.noClasses;
(
packages = "com.example",
importOptions = ImportOption.DoNotIncludeTests.class
)
public class ArchitectureRulesTest {
public static final ArchRule RESTRICT_TIME_MOCKING = noClasses()
.should().callMethod(Time.class, "useMockTime", LocalDateTime.class, ZoneId.class)
.because("Method Time.useMockTime designed only for test purpose and can be used only in the tests");
public static final ArchRule RESTRICT_USAGE_OF_LOCAL_DATE_TIME_NOW = noClasses()
.should().callMethod(LocalDateTime.class, "now")
.because("Use Time.currentDateTime methods instead of as it gives opportunity of mocking time in tests");
public static final ArchRule RESTRICT_USAGE_OF_LOCAL_DATE_NOW = noClasses()
.should().callMethod(LocalDate.class, "now")
.because("Use Time.currentDate methods instead of as it gives opportunity of mocking time in tests");
public static final ArchRule RESTRICT_USAGE_OF_LOCAL_TIME_NOW = noClasses()
.should().callMethod(LocalTime.class, "now")
.because("Use Time.currentTime methods instead of as it gives opportunity of mocking time in tests");
public static final ArchRule RESTRICT_USAGE_OF_OFFSET_DATE_TIME_NOW = noClasses()
.should().callMethod(OffsetDateTime.class, "now")
.because("Use Time.currentOffsetDateTime methods instead of as it gives opportunity of mocking time in tests");
public static final ArchRule RESTRICT_USAGE_OF_ZONED_DATE_TIME_NOW = noClasses()
.should().callMethod(ZonedDateTime.class, "now")
.because("Use Time.currentZonedDateTime methods instead of as it gives opportunity of mocking time in tests");
public static final ArchRule RESTRICT_USAGE_OF_INSTANT_NOW = noClasses()
.should().callMethod(Instant.class, "now")
.because("Use Time.currentInstant methods instead of as it gives opportunity of mocking time in tests");
}
As a bonus, we can also restrict usage of the old Date/Time API:
x
public static final ArchRule RESTRICT_USAGE_OF_OLD_DATE_API = classes()
.that().areNotAssignableTo(OldTimeAdaptor.class)
.should().onlyAccessClassesThat().areNotAssignableTo(Date.class)
.because("java.util.Date is class from the old Date API. " +
"Please use new Date API from the package java.time.* " +
"In case when you need current date/time use wrapper class com.example.utils.Time");
In the case that you use an old library/framework that does not support a new Date/Time API, we can create an adapter class for this purpose. (Please note that exclusion of the adapter class is already defined in the previous rule):
xxxxxxxxxx
package com.example.utils;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;
public class OldTimeAdaptor {
public static LocalDateTime toLocalDateTime(Date date) {
return (date == null) ? null : LocalDateTime.ofInstant(date.toInstant(), ZoneId.systemDefault());
}
public static Date toDate(LocalDateTime localDatetime) {
return localDatetime == null ? null : Date.from(localDatetime.atZone(ZoneId.systemDefault()).toInstant());
}
}
As a final example for the demo, we will create a JUnit 5 extension that automatically mocks time for a predefined value, for instance: 01–04–2020 12:45 Europe/Kiev
xxxxxxxxxx
package com.example.extension;
import com.example.utils.Time;
import org.junit.jupiter.api.extension.AfterEachCallback;
import org.junit.jupiter.api.extension.BeforeEachCallback;
import org.junit.jupiter.api.extension.ExtensionContext;
import java.time.LocalDateTime;
import java.time.Month;
import java.time.ZoneId;
public class MockTimeExtension implements BeforeEachCallback, AfterEachCallback {
public void beforeEach(ExtensionContext extensionContext) throws Exception {
LocalDateTime currentDateTime = LocalDateTime.of(2020, Month.APRIL, 1, 12, 45);
ZoneId zoneId = ZoneId.of("Europe/Kiev");
Time.useMockTime(currentDateTime, zoneId);
}
public void afterEach(ExtensionContext extensionContext) throws Exception {
Time.useSystemDefaultZoneClock();
}
}
Now let's imagine we have a simple method:
xxxxxxxxxx
package com.example.logic;
import com.example.utils.Time;
public class BusinessLogicClass {
public String getLastUpdatedTime() {
return "Last Updated At " + Time.currentDateTime();
}
}
Then we can create a unit test:
xxxxxxxxxx
package com.example.logic;
import com.example.extension.MockTimeExtension;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import static org.assertj.core.api.Assertions.assertThat;
MockTimeExtension.class) (
class BusinessLogicClassTest {
private BusinessLogicClass businessLogicClass = new BusinessLogicClass();
void getLastUpdatedTime_returnMockTime() {
//WHEN
String lastUpdatedTime = businessLogicClass.getLastUpdatedTime();
//THEN
assertThat(lastUpdatedTime).isEqualTo("Last Updated At 2020-04-01T12:45");
}
}
The full source code of the example can be found here: GitHub repository
Published at DZone with permission of Dmytro Stepanyshchenko. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments