java - 测试安卓应用程序。试图模拟 getSystemService。

标签 java android testing mocking mockito

现在已经为此苦苦挣扎了很长一段时间,足以让此处的用户实际上在堆栈上溢出。 我们正在开发一个 android 应用程序,我想测试一个 Activity 类中的方法。我以前做过一些单元测试,但从来没有针对 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 未模拟。”

如有任何帮助,我们将不胜感激。

最佳答案

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

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

关于java - 测试安卓应用程序。试图模拟 getSystemService。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49007114/

相关文章:

java - 重载是编译时多态性。真的吗?

javascript - 我无法在安装了 phonegap 插件的 eclipse 中使用 css、javascript 文件

php - 使用 android volley 和 php 将波斯语值发布到 mysql

java - 更新 AsyncTask 内的 ArrayAdapter 的有效方法?

debugging - isapi 重写调试或测试工具

django - 使用 Django-AllAuth 以编程方式登录?

ios - 通过 TestFlight 安装旧版本

Java RTF 可以导入、编辑和导出吗?

Java Sockets - 发送对象并将对象分发给所有连接的客户端

java - 我们是否应该在 kubernetes 容器中设置 -Xmx(最大 Java 堆大小)