4

I'm developing an Android app and I'm wondering how to unit test an Activity or a Service using GoogleApiClient.

For instance, how to test an Activity or Service in the case GooglePlayService is available and in the case it is unavailable ? I was thinking about using Mockito but since GoogleApiClient is instantiated from inside the Activity, there is no way to mock it (AFAIK).

public class MyService extends Service {
...
private GoogleApiClient googleApiClient;
...
@Override
public void onCreate() {
    ...
    googleApiClient = new GoogleApiClient.Builder(this) ... .build();
    ...
}
...
private void doSomething() {
    if(googleApiClient.isConnected) {
        ...
    }
}

Further more, I've read that mocking a third party library shouldn’t be done because my test suite won't fail if the library is updated but how can I do otherwise ?

PS: I'm sure this question has been asked before but I couldn't find the good keywords :/

Antoine Fontaine
  • 792
  • 7
  • 16

1 Answers1

1

You need mocking. But...

(...) since GoogleApiClient is instantiated from inside the Activity

This, as you already observed, defeats the purpose of mocking and is a potential improvement point. Instantiating external services should happen either via factory (which can then be mocked very easily) or via dependency injection container and passed to class as such (which again can be mocked easily).

Further more, I've read that mocking a third party library shouldn’t be done because my test suite won't fail if the library is updated but how can I do otherwise ?

This is rather strange claim. You will (at least should) have integration tests doing more broad range of component testing where actual 3rd party libraries will be used. In unit test you mock dependencies (any dependencies) in order to test in isolation and focus on unit.

k.m
  • 30,794
  • 10
  • 62
  • 86