How to mock system date with joda time

512 Views Asked by At

I am writing a UI test for a flow that makes use of the current date to do some processing. Here's how I get the current date in my fragment:

val today = dateFormat.format(Date())

In my test, I want to use a fixed date. To this end, I decided to use Joda time. Here's how I implemented it in my test:

@Test
fun testAFlow() {

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

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

    // remainder flow
    ...
}

The test runs fine without breaking but the actual date is still being used instead of the mocked date. How can I fix this?

1

There are 1 best solutions below

2
On BEST ANSWER

You will get fixed date by calling of currentTimeMillis from 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

the behavior of System.currentTimeMillis() will not be changed