Robolectric 3.0: Mocking System.currentTimeMillis ()

I'm trying to change the value returned by System.currentTimeMillis (), so I can perform operations such as: write something to the database, simulate a wait of 5 minutes, make a request in the database (the request depends on when the value is written).

The code suggested in [this SO thread]:

ShadowSystemClock shadowClock = Robolectric.shadowOf(SystemClock.class);
shadowClock.setCurrentTimeMillis(1424369871446);

Does not compile since the removal of the shadowOf method. Try alternatives, for example:

ShadowSystemClock shadowClock = new ShadowSystemClock();
shadowClock.setCurrentTimeMillis(1424369871446);

It looks like there were problems with overriding currentTimeMillis () , but these problems should be fixed since version 3.0.

I could add PowerMock to my project and use it for this case, I think, but if it is possible with Robolectric, I would prefer it.

: , - . :

ShadowSystemClock shadowClock = new ShadowSystemClock();

Log("system = " + System.currentTimeMillis() + "; shadow = " + shadowClock.currentTimeMillis() + "; time from code = " + Code.getSystemTime());

shadowClock.setCurrentTimeMillis(50000000L);

Log("system = " + System.currentTimeMillis() + "; shadow = " + shadowClock.currentTimeMillis() + "; time from code = " + Code.getSystemTime());

:

system = 1438212006879; shadow = 0; time from code = 1438212006894
system = 1438212006898; shadow = 50000000; time from code = 1438212006898

Code.getSystemTime() . System.currentTimeMillis().

, , ShadowSystemClock currentTimeMillis(). ?

+4
2

-, SystemClock - , , shadowOf(). shadowOf() . SystemClock, ShadowSystemClock , ShadowSystemClock new. new shadowClock.currentTimeMillis() ShadowSystemClock.currentTimeMillis().

-, System.currentTimeMillis() - Robolectric , , , , Robolectric. System.currentTimeMillis() ShadowSystemClock.currentTimeMillis(), .

, , , , , , . Robolectric - Android. , , , Robolectric , , @Config - , @Config(instrumentedPackages={ "my.application" }) , Robolectric , "my.application". , , System.currentTimeMillis() ShadowSystemClock.currentTimeMillis(), , .

, -, , , Robolectric classloader, java.lang.*, , . - Robolectric, , , JMockit, . , . , , - , .

, .

+7

Shadows.shadowOf()

-1

All Articles