如何用joda时间模拟系统日期
How to mock system date with joda time
我正在为使用当前日期进行某些处理的流程编写 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
...
}
测试运行良好,没有中断,但仍在使用实际日期而不是模拟日期。我该如何解决这个问题?
您将通过 DateTimeUtils
致电 currentTimeMillis
获得固定日期
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()
的行为不会改变
我正在为使用当前日期进行某些处理的流程编写 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
...
}
测试运行良好,没有中断,但仍在使用实际日期而不是模拟日期。我该如何解决这个问题?
您将通过 DateTimeUtils
currentTimeMillis
获得固定日期
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()
的行为不会改变