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?