测试Android应用程序。试图模拟getSystemService。

问题描述 投票:0回答:1

一直在努力解决这个问题已经有一段时间了,实际上足以让用户在这里堆栈溢出。我们正在开发一个Android应用程序,我想在一个活动类中测试一个方法。我以前做过一些单元测试,但从来没有用过android项目,我以前从未尝试过嘲笑。

我正在尝试测试的方法:

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

此方法检查Android设备是否启用了GPS,如果是,则返回true,否则返回false。我正在尝试模拟LocationManager和Context,这是我到目前为止所做的:

@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());
    }
}

当我运行此测试时,我收到此错误:

“java.lang.RuntimeException:android.app.Activity中的方法getSystemService没有被模拟。”

任何有关这方面的帮助将不胜感激。

java android testing mocking mockito
1个回答
0
投票

将模拟的上下文传递给活动中的方法。

    @Test
    public void isGpsOn() {
        final Context context = mock(Context.class);
        final LocationManager manager = mock(LocationManager.class);
        Mockito.when(context.getSystemService(Context.LOCATION_SERVICE)).thenReturn(manager);
        Mockito.when(manager.isProviderEnabled(LocationManager.GPS_PROVIDER)).thenReturn(true);
        assertTrue(activity.isGpsEnabled(context));
    }
© www.soinside.com 2019 - 2024. All rights reserved.