mixpanel / mixpanel-android

Official Android Tracking Library for Mixpanel Analytics
http://mixpanel.com/
Apache License 2.0
1.02k stars 365 forks source link

Feature request: "Dry run" / Testability #591

Closed alixwar closed 4 years ago

alixwar commented 5 years ago

I feel that MixpanelAPI is lacking in terms of testability.

Situation right now (5.5.1)

Workaround

Suggestions (alternatives)

patedit commented 5 years ago

Thanks a lot for the suggestion! So I understand it a bit better, can you pass a mock context when creating a Mixpanel instance?

alwa commented 5 years ago

@patedit Yes, Robolectric can create such fake contexts

alixwar commented 5 years ago

@patedit Any updates on this?

alixwar commented 5 years ago

My workaround:

New class:

package com.mixpanel.android.mpmetrics;

// Imports...
public class StubbedMixpanelAPI extends MixpanelAPI {

    @SuppressLint("NewApi")
    public StubbedMixpanelAPI(@NonNull Context context) {
        super(context, CompletableFuture.completedFuture(
                context.getSharedPreferences("dummy", Context.MODE_PRIVATE)), "", true);
    }

}

When I instantiate MixpanelAPI:

...

isRoboUnitTest() ? new StubbedMixpanelAPI(context) : MixpanelAPI.getInstance(context, BuildConfig.ANALYTICS_TOKEN, false);

...

private static boolean isRoboUnitTest() {
   return "robolectric".equals(Build.FINGERPRINT);
}
patedit commented 4 years ago

Thanks for the snippet @alixwar. Sadly adding this feature is not on our roadmap and since there is an existing workaround, other devs will find this useful.

alixwar commented 3 years ago

With the new "Looper mode" in Robolectric, the workaround is now broken unfortunately