2

I have an Activity that calls AccountManager.get(this) giving me an instance of the AccountManager to call getAuthTokenByFeatures().

I want to test this activity and mock the different responses that the Account manager could give me.

Using the AndroidJUnit4 tests, how can I break this dependency and inject a mock account manager into my activity?

I found this answer which goes into how to create a ContextWrapper to change the getSystemService() implementation. However the answer uses the ActivityUnitTestCase which has been deprecated. Is there a way to do it with the AndroidJUnit4 tests?

Activity under test:

public class SplashActivity extends AbstractActivity implements SplashView {

    private static final String TAG = SplashActivity.class.getSimpleName();
    private AccountManager accountManager;

    @Override
    protected void onCreate(@Nullable final Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_splash);

        accountManager = AccountManager.get(this);
        accountManager.getAuthTokenByFeatures(
                ACCOUNT_TYPE,
                AccountConstants.AUTH_TOKEN_TYPE_MAIN,
                null,
                this,
                null,
                null,
                new AccountManagerCallback<Bundle>() {
                    @Override
                    public void run(AccountManagerFuture<Bundle> future) {
                        try {
                            Bundle bundle = future.getResult();
                            Log.d(TAG, "Created Authentication token: "
                                    + bundle.getString(AccountManager.KEY_AUTHTOKEN));
                            launchHomeScreen();
                        } catch (OperationCanceledException e) {
                            showAuthorizationError();
                        } catch (IOException | AuthenticatorException e) {
                            showAuthorizationError();
                        }
                    }
                },
                null);
    }

    @Override
    public void launchHomeScreen() {
        HomeActivity.start(this);
    }

    @Override
    public void showAuthorizationError() {
        new AlertDialog.Builder(this)
                .setMessage(R.string.vt_alert_authorization_failed)
                .setNeutralButton(R.string.vt_ok, null)
                .create()
                .show();
    }
}
Community
  • 1
  • 1
MungoRae
  • 1,912
  • 1
  • 16
  • 25

0 Answers0