问题
I've just started to use Robolectric and wanted to know how to resolve Google Play Services. I'm using Robolectric 3 RC2, and my gradle is as follow :
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'
I'm running a method from my project to get json from an API. When calling it, I pass the advertising 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();
}
The main part of my test is :
@Test(timeout = 7000)
public void jsonLoading() {
try {
client.loadData(this);
} catch (Exception e){
ex = e;
}
assertNull(ex);
//wait for task code
ShadowApplication.runBackgroundTasks();
Each time I run the test, I've got the GooglePlayServicesNotAvailableException
(from e.printStackTrace();
) and I'm unable to solve it AND to assert it so the test will not pass.
I've haven't find any clue to debug my code.
回答1:
I ran into this the other day.
Use:
testCompile 'org.robolectric:shadows-play-services:3.0'
testCompile 'org.robolectric:shadows-support-v4:3.0'
And see this example:
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 {
}
回答2:
For folks trying to use GoogleApiAvailability with Robolectric...
gradle
dependencies {
testApi 'org.robolectric:robolectric:3.6.1'
testApi 'org.robolectric:shadows-playservices:3.6.1'
}
Code
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 {
}
回答3:
I don't think you can use Google play services with robolectric, you will need shadows.
来源:https://stackoverflow.com/questions/29915790/robolectric-3-googleplayservicesnotavailableexception