我刚开始使用Robolectric,想知道如何解决 Google Play服务。我正在使用 Robolectric 3 RC2 ,我的gradle如下:
build.bradle
compile 'com.squareup.okhttp:okhttp:2.3.0'
compile 'com.google.android.gms:play-services:7.0.0'
testCompile ("org.robolectric:robolectric:3.0-rc2"){
exclude module: 'commons-logging'
exclude module: 'httpclient'
}
testCompile ("org.robolectric:shadows-play-services:3.0-rc2"){
exclude module: 'commons-logging'
exclude module: 'httpclient'
}
testCompile 'com.squareup.okhttp:mockwebserver:1.2.1'
我正在从我的项目中运行一个方法来从API中获取json。在拨打电话时,我会传递广告ID:
AdvertisingIdClient.Info adInfo = null;
try {
adInfo = AdvertisingIdClient.getAdvertisingIdInfo(mContext);
} catch (IOException |
GooglePlayServicesNotAvailableException |
GooglePlayServicesRepairableException e) {
// Unrecoverable error connecting to Google Play services (e.g.,
// the old version of the service doesn't support getting AdvertisingId).
e.printStackTrace();
}
我测试的主要部分是:
@Test(timeout = 7000)
public void jsonLoading() {
try {
client.loadData(this);
} catch (Exception e){
ex = e;
}
assertNull(ex);
//wait for task code
ShadowApplication.runBackgroundTasks();
每次运行测试时,我都会得到GooglePlayServicesNotAvailableException
(来自e.printStackTrace();
)而我无法解决并且断言< / strong>它所以测试不会通过。
我找不到调试代码的任何线索。
答案 0 :(得分:3)
我前几天碰到了这个。
testCompile 'org.robolectric:shadows-play-services:3.0'
testCompile 'org.robolectric:shadows-support-v4:3.0'
public class TestBase {
@Before
public void setUp() throws Exception {
// Turn off Google Analytics - Does not need to work anymore
final ShadowApplication shadowApplication = Shadows.shadowOf(RuntimeEnvironment.application);
shadowApplication.declareActionUnbindable("com.google.android.gms.analytics.service.START");
// Force success
ShadowGooglePlayServicesUtil.setIsGooglePlayServicesAvailable(ConnectionResult.SUCCESS);
}
@After
public void tearDown() throws Exception {
}
}
public MyTestClass extends TestBase {
}
答案 1 :(得分:1)
对于尝试在Robolectric中使用GoogleApiAvailability的人......
<强> gradle这个强>
dependencies {
testApi 'org.robolectric:robolectric:3.6.1'
testApi 'org.robolectric:shadows-playservices:3.6.1'
}
<强>代码强>
public class TestBase {
@Before
public void setUp() throws Exception {
final ShadowGoogleApiAvailability shadowGoogleApiAvailability
= Shadows.shadowOf(GoogleApiAvailability.getInstance());
shadowGoogleApiAvailability.setIsGooglePlayServicesAvailable(ConnectionResult.SUCCESS);
}
@After
public void tearDown() throws Exception {
}
}
public MyTestClass extends TestBase {
}