Closed alixwar closed 4 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?
@patedit Yes, Robolectric can create such fake contexts
@patedit Any updates on this?
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);
}
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.
With the new "Looper mode" in Robolectric, the workaround is now broken unfortunately
I feel that
MixpanelAPI
is lacking in terms of testability.Situation right now (5.5.1)
MixpanelAPI
is notfinal
which is good (= Possible to mock without bytecode manipulation)MixpanelAPI
does not have a public constructor (= Not possible to create dummy subclasses)MixpanelAPI.getInstance()
returnsnull
under Robolectric ( = Tests fail due to NPE)Workaround
MixpanelAPI
where the tests replace the "real" instance (=null
) with a mock instanceSuggestions (alternatives)
mixpanel-android-mock
with an API that configures Mixpanel ("dry run") to return reasonable dummy objects. Example of such library: https://github.com/square/retrofit/tree/master/retrofit-mock