mardi 27 février 2018

Testing android app. Trying to mock getSystemService.

Have been struggling with this for quite some time now, enough to make a user here on stack overflow actually. We're developing an android application, and I want to test a method inside an activity class. I have done some unit testing before, but never for an android project, and I've never tried mocking before.

The method I'm trying to test:

public boolean isGPSEnabled()
{
    LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    GPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
    return GPSEnabled;
}

This method checks if the android device got the GPS enabled and returns true if it is, false if not. I'm trying to mock the LocationManager and the Context, and this is what I have so far:

@RunWith(MockitoJUnitRunner.class)

public class IsGPSEnabledTest
{

    @Mock
    LocationManager locationManagerMock = mock(LocationManager.class);
    MockContext contextMock = mock(MockContext.class);

    @Test
    public void testGPSEnabledTrue() throws Exception
    {
        when(contextMock.getSystemService(Context.LOCATION_SERVICE)).thenReturn(locationManagerMock);
        when(locationManagerMock.isProviderEnabled(LocationManager.GPS_PROVIDER)).thenReturn(true);        

        MapsActivity activity = new MapsActivity();
        assertEquals(true, activity.isGPSEnabled());
    }
}

When I run this test I get this error:

"java.lang.RuntimeException: Method getSystemService in android.app.Activity not mocked."

Any help on this would be appreciated.

1 commentaire: