Android Testing — Setting SharedPrefs before launching an Activity

The Problem:

I want to create a UI test to verify that text views are populated with the correct data.

The textviews are populated with data from SharedPreferences during 0nCreate.

Because the data population happens during onCreate, the SharedPreferences need to be set up before launching the activity.

Solution:

We start by setting up the test rule for espresso.

@Rule
public ActivityTestRule<AccountInfoActivity> mActivityRule = new ActivityTestRule<>(
AccountInfoActivity.class,
true,
false);

Notice how I’m not starting the activity immediately — this is crucial, as we need to set up the SharedPrefs before launching the activity.

Next, We access the target context (context of the app under test, not the test app!):

Context context = getInstrumentation().getTargetContext();

And then we create the SharedPrefs editor (in my case the DefaultSharedPrefs) with the following:

preferencesEditor = PreferenceManager.getDefaultSharedPreferences(context).edit();

With the editor now available, we can set the data

// Set SharedPreferences data
preferencesEditor.putString("username", "TestUsername");
preferencesEditor.commit();

And finally launch the activity:

// Launch activity
mActivityRule.launchActivity(intent);

Code Sample:

@RunWith(AndroidJUnit4.class)
@LargeTest
public class AccountInfoActivityTest {

Intent intent;
SharedPreferences.Editor preferencesEditor;

@Rule
public ActivityTestRule<AccountInfoActivity> mActivityRule = new ActivityTestRule<>(
AccountInfoActivity.class,
true,
false); // Activity is not launched immediately

@Before
public void setUp() {
Context targetContext = getInstrumentation().getTargetContext();
preferencesEditor = PreferenceManager.getDefaultSharedPreferences(targetContext).edit();
}

@Test
public void populateUsernameFromSharedPrefsTest() {
preferencesEditor.putString("username", "testUsername");
preferencesEditor.commit();

// Launch activity
mActivityRule.launchActivity(new Intent());

onView(withId(R.id.textview_account_username))
.check(matches(isDisplayed()))
.check(matches(withText(testUsername)));
}
}

Hope it helps!

Software Development Engineer in Test

Software Development Engineer in Test