gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 10:18:54 25 4
gpt4 key购买 nike

现在已经为此苦苦挣扎了很长一段时间,足以让此处的用户实际上在堆栈上溢出。我们正在开发一个 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com