jack_the_beast
jack_the_beast

Reputation: 1971

Android Unit Test: mocking System.currentTimeMillis()

I'm learning how to write unit tests and I've run into some problems.

Basically, my method set an alarm based on the system clock, so in the test I want to mock the System class. I tried as this answer says. So here's my test:

@RunWith(PowerMockRunner.class)
public class ApplicationBackgroundUtilsTest {
    @Mock
    private Context context;

    @Mock
    private AlarmManager alarmManager;

    @Before
    public void setup() {
        MockitoAnnotations.initMocks(this);
    }

    @Test
    public void registerAlarmManagerTest() {
        PowerMockito.mockStatic(System.class);
        when(context.getSystemService(Context.ALARM_SERVICE)).thenReturn(alarmManager);
        BDDMockito.given(System.currentTimeMillis()).willReturn(0L);

        ApplicationBackgroundUtils.getInstance().registerAlarmManager(context);

        verify(alarmManager, times(1)).set(eq(AlarmManager.RTC_WAKEUP), eq(120L), any(PendingIntent.class));

    }

So with this code I'm expecting System.currentTimeMillis() to always return 0 but instead I get this:

Comparison Failure: 
Expected :alarmManager.set(0, 120, <any>);
Actual   :alarmManager.set(0, 1524564129683, null);

so I'm guessing the mocking of System is not working.

How can I do this?

Upvotes: 1

Views: 4571

Answers (2)

jack_the_beast
jack_the_beast

Reputation: 1971

Turns out I just missed @PrepareForTest(ApplicationBackgroundUtils.class)before the class declaration.

I think it prepares the class to be tested to use the mocks, but if anyone wants to further clarify that is welcome.

EDIT: Thanks to pavithraCS:

@PrepareForTest annotation is used by powermock to prepare the specified class or classes for testing. It will perform bytecode manipualtions to the given class to enable mocking of final classes, static methods.. etc.

Upvotes: 0

pavithraCS
pavithraCS

Reputation: 691

@PrepareForTest annotation is used by powermock to prepare the specified class or classes for testing. It will perform bytecode manipualtions to the given class to enable mocking of final classes, static methods.. etc.

Upvotes: 1

Related Questions