Bja*_*ent 3 java testing android mocking mockito
现在已经在这个问题上挣扎了很长一段时间,足以让用户实际上出现堆栈溢出。我们正在开发一个 Android 应用程序,我想测试活动类中的一个方法。我以前做过一些单元测试,但从来没有针对android项目做过,而且我以前从未尝试过mock。
我正在尝试测试的方法:
public boolean isGPSEnabled()
{
LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
GPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
return GPSEnabled;
}
Run Code Online (Sandbox Code Playgroud)
此方法检查 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());
}
}
Run Code Online (Sandbox Code Playgroud)
当我运行此测试时,我收到此错误:
“java.lang.RuntimeException:android.app.Activity 中的方法 getSystemService 未被模拟。”
对此的任何帮助将不胜感激。
小智 5
将模拟上下文传递给活动中的方法。
@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));
}
Run Code Online (Sandbox Code Playgroud)