Android Testing — Setting SharedPrefs before launching an Activity
Szymon Kazmierczak

Hi, thanks you so much. Your post helped me a lot!

I changed your implementation a bit, I think that you can improve it creating a custom test rule to avoid call launchActivity on every single test.

This is my implementation using yours :

public class LoginActivityTestRule<T extends Activity> extends ActivityTestRule<T> {

SharedPreferences.Editor editor;
Context context;

public LoginActivityTestRule(Class<T> activityClass) {

public LoginActivityTestRule(Class<T> activityClass, boolean initialTouchMode) {
this(activityClass, initialTouchMode,true);

public LoginActivityTestRule(Class<T> activityClass, boolean initialTouchMode,
boolean launchActivity) {
super(activityClass, initialTouchMode, launchActivity);
this.context = InstrumentationRegistry.getTargetContext();
this.editor = PreferenceManager.getDefaultSharedPreferences(this.context).edit();

@Override protected void beforeActivityLaunched() {
//put your values here

I try to use getActivity() method to retrieve the context but activity it’s not created until launchActivity is executed. Anyway, like activity specific context is not needed to retrieve shared preferences you can use the appContext.

One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.