Mocking time in Java 8's java.time API

后端 未结 8 1697
我寻月下人不归
我寻月下人不归 2020-11-27 16:09

Joda Time has a nice DateTimeUtils.setCurrentMillisFixed() to mock time.

It\'s very practical in tests.

Is there an equivalent in Java 8\'s java.time API

8条回答
  •  盖世英雄少女心
    2020-11-27 16:50

    I need LocalDate instance instead of LocalDateTime.
    With such reason I created following utility class:

    public final class Clock {
        private static long time;
    
        private Clock() {
        }
    
        public static void setCurrentDate(LocalDate date) {
            Clock.time = date.toEpochDay();
        }
    
        public static LocalDate getCurrentDate() {
            return LocalDate.ofEpochDay(getDateMillis());
        }
    
        public static void resetDate() {
            Clock.time = 0;
        }
    
        private static long getDateMillis() {
            return (time == 0 ? LocalDate.now().toEpochDay() : time);
        }
    }
    

    And usage for it is like:

    class ClockDemo {
        public static void main(String[] args) {
            System.out.println(Clock.getCurrentDate());
    
            Clock.setCurrentDate(LocalDate.of(1998, 12, 12));
            System.out.println(Clock.getCurrentDate());
    
            Clock.resetDate();
            System.out.println(Clock.getCurrentDate());
        }
    }
    

    Output:

    2019-01-03
    1998-12-12
    2019-01-03
    

    Replaced all creation LocalDate.now() to Clock.getCurrentDate() in project.

    Because it is spring boot application. Before test profile execution just set a predefined date for all tests:

    public class TestProfileConfigurer implements ApplicationListener {
        private static final LocalDate TEST_DATE_MOCK = LocalDate.of(...);
    
        @Override
        public void onApplicationEvent(ApplicationPreparedEvent event) {
            ConfigurableEnvironment environment = event.getApplicationContext().getEnvironment();
            if (environment.acceptsProfiles(Profiles.of("test"))) {
                Clock.setCurrentDate(TEST_DATE_MOCK);
            }
        }
    }
    

    And add to spring.factories:

    org.springframework.context.ApplicationListener=com.init.TestProfileConfigurer

提交回复
热议问题