1

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?

jack_the_beast
  • 1,838
  • 4
  • 34
  • 67

2 Answers2

1

@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.

pavithraCS
  • 709
  • 6
  • 23
0

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.

jack_the_beast
  • 1,838
  • 4
  • 34
  • 67
  • You are welcome :) For more information https://static.javadoc.io/org.powermock/powermock-core/1.6.5/org/powermock/core/classloader/annotations/PrepareForTest.html – pavithraCS Apr 25 '18 at 03:55