I have started to work with unit tests and still I do not know how to test somethings . My app has a method that receives 2 params, the opening and the closing time of a venue and returns true if the venue is open at the current time or false otherwise. Internally that method uses Calendar c = Calendar.getInstance();
to get the current time. To test properly that method, how can a set time that I want the Calendar class returns? I know that in Microsoft Fakes framework there is something called shims
that fakes the return values of system classes. Do you know any similar technology in Robolectric framework?.

- 441
- 2
- 6
- 17
-
Did you find a solution for this? We're running into the same problem. – Leslie Chong Feb 17 '15 at 23:06
2 Answers
Robolectric replaces some of the framework classes with so-called shadow classes. These classes often allow to specify their behaviour in order to test code that uses the original framework classes.
In this case, the shadow class you are looking for is called ShadowSystemClock which has a setCurrentTimeMillis() which you can use to specify the return value of currentTimeMillis() which Calendar uses.
Something along the lines of:
ShadowSystemClock shadowClock = Robolectric.shadowOf(SystemClock.class);
shadowClock.setCurrentTimeMillis(1424369871446); // 18:17:51 UTC Feb 19 2015
should work for you.
EDIT:
Now the methods of ShadowSystemClock
can be accessed directly as they are now static. The updated way to set the time would be:
ShadowSystemClock.setCurrentTimeMillis(1424369871446); // 18:17:51 UTC Feb 19 2015
As quoted in this issue - Calls to java.lang.System are not intercepted in Robolectric
The effect of the above code is evident on other methods like:
ShadowSystemClock.currentTimeMillis();
SystemClock.currentThreadTimeMillis();
As of now, there is no straightforward way to mock the response of System.currentTimeMillis()
, until the status of the issue linked above changes.

- 7,661
- 4
- 30
- 55

- 51
- 2
-
-
`ShadowSystemClock.setCurrentTimeMillis(1424369871446);`. All methods are now static. – Kamran Ahmed Nov 21 '17 at 08:08
-
2@Edward @KamranAhmed, this is doesn't work for me. I set `ShadowSystemClock.setCurrentTimeMillis(1424369871446);` Then call `Calendar.getInstance().getTimeInMillis()` and it returns real time. Could anyone help me? – AinisSK Dec 05 '17 at 17:41
What I did was the next:
First I created a class that wraps the interactions with Dates like in this post: link
Then I mocked the method that returns today(Date) like this with Mockito:
public void setMockDate(String mockDateString) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
try {
Date mockDate = sdf.parse(mockDateString);
stub(mockDateProvider.getToday()).toReturn(mockDate);
} catch (ParseException parseException) {
fail("Failure: Unable to parse test date string");
}}
then you can specify a date that the method will return.
Hope it helps to others!

- 1
- 1

- 1,894
- 18
- 38