首页 > 解决方案 > 如何使用 joda 时间模拟系统日期

问题描述

我正在为使用当前日期进行一些处理的流程编写 UI 测试。这是我在片段中获取当前日期的方法:

val today = dateFormat.format(Date())

在我的测试中,我想使用一个固定的日期。为此,我决定使用Joda time。这是我在测试中实现它的方式:

@Test
fun testAFlow() {

    // setting date to fixed value
    DateTimeUtils.setCurrentMillisFixed(1610248674000)

    // launching activity
    activityRule.launchActivity(Intent())

    // remainder flow
    ...
}

测试运行良好而不会中断,但仍在使用实际日期而不是模拟日期。我怎样才能解决这个问题?

标签: androidandroid-espressoandroid-jodatime

解决方案


您将通过调用currentTimeMillisfrom获得固定日期DateTimeUtils

Log.d(BuildConfig.app_tag,"time " + DateTimeUtils.currentTimeMillis()); // output: current time millis

DateTimeUtils.setCurrentMillisFixed(1610248674000L);
    
Log.d(BuildConfig.app_tag,"time " + DateTimeUtils.currentTimeMillis()); // output: 1610248674000

的行为System.currentTimeMillis()不会改变


推荐阅读