mardi 29 décembre 2015

Android ServiceTestCase run service by context

I've got class which serves as a public API for the lib I've written. Now I want to write unit tests and call the methods of that class, here is the snippet of it:

public final class Analytics {

    public static void init(Context context,
                            @NonNull String appId,
                            @NonNull String deviceID,
                            @NonNull String countryCode,
                            @NonNull String market) {
        Intent analyticsIntent = new Intent(context, PAanalyticsService.class)
                .putExtra("app_id", appId)
                .putExtra("device_id", deviceID)
                .putExtra("country_code", countryCode)
                .putExtra("market", market);

        context.bindService(analyticsIntent, new ServiceConnection() {
            @Override
            public void onServiceConnected(ComponentName name, IBinder service) {
            }

            @Override
            public void onServiceDisconnected(ComponentName name) {
            }
        }, Context.BIND_AUTO_CREATE);
    }

    public static void setUserId(Context context, long userId) {
        Intent intent = new Intent(context, PAanalyticsService.class)
                .setAction(Constants.UPDATE_USER_ACTION)
                .putExtra("user_id", userId);

        context.startService(intent);
    }
}

The problem is that in my methods service is started by context, so if I call Analytics class methods from my unit tests service won't be run, I must call startService()/bindService of ServiceTestCase for running PAanalyticsService, but in that case I lose the opportunity to call the methods of my class.

Aucun commentaire:

Enregistrer un commentaire