DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Because the DevOps movement has redefined engineering responsibilities, SREs now have to become stewards of observability strategy.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Related

  • Selenium Grid Tutorial: Essential Tips and How to Set It Up
  • Automating Cucumber Data Table to Java Object Mapping in Your Cucumber Tests
  • JUnit 5 Custom TestListeners
  • Integrate Cucumber in Playwright With Java

Trending

  • Security by Design: Building Full-Stack Applications With DevSecOps
  • How To Build Resilient Microservices Using Circuit Breakers and Retries: A Developer’s Guide To Surviving
  • Introducing Graph Concepts in Java With Eclipse JNoSQL, Part 3: Understanding Janus
  • IoT and Cybersecurity: Addressing Data Privacy and Security Challenges
  1. DZone
  2. Coding
  3. Java
  4. Mock Java Date/Time for Testing

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.

By 
Dmytro Stepanyshchenko user avatar
Dmytro Stepanyshchenko
·
Jan. 27, 21 · Tutorial
Likes (2)
Comment
Save
Tweet
Share
57.7K Views

Join the DZone community and get the full member experience.

Join For Free

Referencing 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().

Java
 




x


 
1
LocalDate.now();
2
LocalTime.now();
3
LocalDateTime.now();
4
OffsetDateTime.now();
5
ZonedDateTime.now();
6
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:

Java
 




xxxxxxxxxx
1
14


 
1
    /**
2
     * Obtains the current time from the system clock in the default time-zone.
3
     * <p>
4
     * This will query the {@link Clock#systemDefaultZone() system clock} in the default
5
     * time-zone to obtain the current time.
6
     * <p>
7
     * Using this method will prevent the ability to use an alternate clock for testing
8
     * because the clock is hard-coded.
9
     *
10
     * @return the current time using the system clock and default time-zone, not null
11
     */
12
    public static LocalTime now() {
13
        return now(Clock.systemDefaultZone());
14
    }



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:

Java
 




x
52


 
1
package com.example.utils;
2

           
3
import java.time.*;
4
import java.util.TimeZone;
5

           
6
public class Time {
7
    private static Clock CLOCK = Clock.systemDefaultZone();
8
    private static final TimeZone REAL_TIME_ZONE = TimeZone.getDefault();
9

           
10
    public static LocalDate currentDate() {
11
        return LocalDate.now(getClock());
12
    }
13

           
14
    public static LocalTime currentTime() {
15
        return LocalTime.now(getClock());
16
    }
17

           
18
    public static LocalDateTime currentDateTime() {
19
        return LocalDateTime.now(getClock());
20
    }
21

           
22
    public static OffsetDateTime currentOffsetDateTime() {
23
        return OffsetDateTime.now(getClock());
24
    }
25

           
26
    public static ZonedDateTime currentZonedDateTime() {
27
        return ZonedDateTime.now(getClock());
28
    }
29

           
30
    public static Instant currentInstant() {
31
        return Instant.now(getClock());
32
    }
33

           
34
    public static long currentTimeMillis() {
35
        return currentInstant().toEpochMilli();
36
    }
37

           
38
    public static void useMockTime(LocalDateTime dateTime, ZoneId zoneId) {
39
        Instant instant = dateTime.atZone(zoneId).toInstant();
40
        CLOCK = Clock.fixed(instant, zoneId);
41
        TimeZone.setDefault(TimeZone.getTimeZone(zoneId));
42
    }
43

           
44
    public static void useSystemDefaultZoneClock() {
45
        TimeZone.setDefault(REAL_TIME_ZONE);
46
        CLOCK = Clock.systemDefaultZone();
47
    }
48

           
49
    private static Clock getClock() {
50
        return CLOCK;
51
    }
52
}



Let's look into the wrapper class more closely:

  1. First of all, we remember the system clock and system timezone.
  2. Using method userMockTime() we can override time with the fixed clock and provide the time zone.
  3. Using method useSystemDefaultZoneClock() we can reset the clock and the timezone to the system defaults.
  4. All other methods use the provided clock instance.

So far so good, but there are two problems left in this approach:

  1. TheuseMockTime() method is too dangerous for the production code. What we want is to somehow eliminate the usage of that method in the source code.
  2. 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):

XML
 




xxxxxxxxxx
1


 
1
<dependency>
2
    <groupId>com.tngtech.archunit</groupId>
3
    <artifactId>archunit-junit5</artifactId>
4
    <version>0.14.1</version>
5
    <scope>test</scope>
6
</dependency>



And add rule descriptions in the unit test folder:

Java
 




xxxxxxxxxx
1
56


 
1
package com.example;
2

           
3
import com.example.utils.OldTimeAdaptor;
4
import com.example.utils.Time;
5
import com.tngtech.archunit.core.importer.ImportOption;
6
import com.tngtech.archunit.junit.AnalyzeClasses;
7
import com.tngtech.archunit.junit.ArchTest;
8
import com.tngtech.archunit.lang.ArchRule;
9

           
10
import java.time.*;
11
import java.util.Date;
12

           
13
import static com.tngtech.archunit.lang.syntax.ArchRuleDefinition.classes;
14
import static com.tngtech.archunit.lang.syntax.ArchRuleDefinition.noClasses;
15

           
16
@AnalyzeClasses(
17
        packages = "com.example",
18
        importOptions = ImportOption.DoNotIncludeTests.class
19
)
20
public class ArchitectureRulesTest {    
21
    @ArchTest
22
    public static final ArchRule RESTRICT_TIME_MOCKING = noClasses()
23
            .should().callMethod(Time.class, "useMockTime", LocalDateTime.class, ZoneId.class)
24
            .because("Method Time.useMockTime designed only for test purpose and can be used only in the tests");
25
    
26

           
27
    @ArchTest
28
    public static final ArchRule RESTRICT_USAGE_OF_LOCAL_DATE_TIME_NOW = noClasses()
29
            .should().callMethod(LocalDateTime.class, "now")
30
            .because("Use Time.currentDateTime methods instead of as it gives opportunity of mocking time in tests");
31

           
32
    @ArchTest
33
    public static final ArchRule RESTRICT_USAGE_OF_LOCAL_DATE_NOW = noClasses()
34
            .should().callMethod(LocalDate.class, "now")
35
            .because("Use Time.currentDate methods instead of as it gives opportunity of mocking time in tests");
36

           
37
    @ArchTest
38
    public static final ArchRule RESTRICT_USAGE_OF_LOCAL_TIME_NOW = noClasses()
39
            .should().callMethod(LocalTime.class, "now")
40
            .because("Use Time.currentTime methods instead of as it gives opportunity of mocking time in tests");
41

           
42
    @ArchTest
43
    public static final ArchRule RESTRICT_USAGE_OF_OFFSET_DATE_TIME_NOW = noClasses()
44
            .should().callMethod(OffsetDateTime.class, "now")
45
            .because("Use Time.currentOffsetDateTime methods instead of as it gives opportunity of mocking time in tests");
46

           
47
    @ArchTest
48
    public static final ArchRule RESTRICT_USAGE_OF_ZONED_DATE_TIME_NOW = noClasses()
49
            .should().callMethod(ZonedDateTime.class, "now")
50
            .because("Use Time.currentZonedDateTime methods instead of as it gives opportunity of mocking time in tests");
51

           
52
    @ArchTest
53
    public static final ArchRule RESTRICT_USAGE_OF_INSTANT_NOW = noClasses()
54
            .should().callMethod(Instant.class, "now")
55
            .because("Use Time.currentInstant methods instead of as it gives opportunity of mocking time in tests");
56
}



As a bonus, we can also restrict usage of the old Date/Time API:

Java
 




x


 
1
    @ArchTest
2
    public static final ArchRule RESTRICT_USAGE_OF_OLD_DATE_API = classes()
3
            .that().areNotAssignableTo(OldTimeAdaptor.class)
4
            .should().onlyAccessClassesThat().areNotAssignableTo(Date.class)
5
            .because("java.util.Date is class from the old Date API. " +
6
                    "Please use new Date API from the package java.time.* " +
7
                    "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):

Java
 




xxxxxxxxxx
1
16


 
1
package com.example.utils;
2

           
3
import java.time.LocalDateTime;
4
import java.time.ZoneId;
5
import java.util.Date;
6

           
7
public class OldTimeAdaptor {
8
    public static LocalDateTime toLocalDateTime(Date date) {
9
        return (date == null) ? null : LocalDateTime.ofInstant(date.toInstant(), ZoneId.systemDefault());
10
    }
11

           
12
    public static Date toDate(LocalDateTime localDatetime) {
13
        return localDatetime == null ? null : Date.from(localDatetime.atZone(ZoneId.systemDefault()).toInstant());
14
    }
15
}



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

Java
 




xxxxxxxxxx
1
25


 
1
package com.example.extension;
2

           
3
import com.example.utils.Time;
4
import org.junit.jupiter.api.extension.AfterEachCallback;
5
import org.junit.jupiter.api.extension.BeforeEachCallback;
6
import org.junit.jupiter.api.extension.ExtensionContext;
7

           
8
import java.time.LocalDateTime;
9
import java.time.Month;
10
import java.time.ZoneId;
11

           
12
public class MockTimeExtension implements BeforeEachCallback, AfterEachCallback {
13
    @Override
14
    public void beforeEach(ExtensionContext extensionContext) throws Exception {
15
        LocalDateTime currentDateTime = LocalDateTime.of(2020, Month.APRIL, 1, 12, 45);
16
        ZoneId zoneId = ZoneId.of("Europe/Kiev");
17

           
18
        Time.useMockTime(currentDateTime, zoneId);
19
    }
20

           
21
    @Override
22
    public void afterEach(ExtensionContext extensionContext) throws Exception {
23
        Time.useSystemDefaultZoneClock();
24
    }
25
}



Now let's imagine we have a simple method:

Java
 




xxxxxxxxxx
1


 
1
package com.example.logic;
2

           
3
import com.example.utils.Time;
4

           
5
public class BusinessLogicClass {
6
    public String getLastUpdatedTime() {
7
        return "Last Updated At " + Time.currentDateTime();
8
    }
9
}



Then we can create a unit test:

Java
 




xxxxxxxxxx
1
21


 
1
package com.example.logic;
2

           
3
import com.example.extension.MockTimeExtension;
4
import org.junit.jupiter.api.Test;
5
import org.junit.jupiter.api.extension.ExtendWith;
6

           
7
import static org.assertj.core.api.Assertions.assertThat;
8

           
9
@ExtendWith(MockTimeExtension.class)
10
class BusinessLogicClassTest {
11
    private BusinessLogicClass businessLogicClass = new BusinessLogicClass();
12

           
13
    @Test
14
    void getLastUpdatedTime_returnMockTime() {
15
        //WHEN
16
        String lastUpdatedTime = businessLogicClass.getLastUpdatedTime();
17

           
18
        //THEN
19
        assertThat(lastUpdatedTime).isEqualTo("Last Updated At 2020-04-01T12:45");
20
    }
21
}



The full source code of the example can be found here: GitHub repository

Java (programming language) Testing

Published at DZone with permission of Dmytro Stepanyshchenko. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Selenium Grid Tutorial: Essential Tips and How to Set It Up
  • Automating Cucumber Data Table to Java Object Mapping in Your Cucumber Tests
  • JUnit 5 Custom TestListeners
  • Integrate Cucumber in Playwright With Java

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!