Clear Shared Preferences In Android Espresso Tests — Kotlin

Shraddha Gupta
2 min readNov 27, 2020

While writing automation tests for android applications ,sometimes we need to clear all the shared preferences added during our tests.

We might run into a situation where your app under test will go to screen A if it is first launch and to screen B if user has already logged in once and login credentials are stored in a shared preference file .

So in this situation we will need to clear the shared preferences before running a test.

You can do this by following the below steps:

  1. Set up the test rule for espresso tests:
@Rule
@JvmField
val activityTestRule = ActivityTestRule(StartupActivity::class.java, false, false)

We need to clear shared prefs before launching the activity ,so it’s important to pass false for launch activity parameter.

2. Access the target context of the app under test.

val context = InstrumentationRegistry.getInstrumentation().targetContext

3. Clearing Shared preferences from default :


val sharedPrefs = PreferenceManager.getDefaultSharedPreferences(context)
val editor = sharedPrefs.edit()
editor.clear()
editor.apply()

4. Clearing shared preferences from your shared preference instead of default:

val sharedPrefs = context.getSharedPreferences(YOUR_SHARED_PREFERENCES_NAME, Context.MODE_PRIVATE) // 
val editor = sharedPrefs.edit()
editor.clear()
editor.apply()

Code snippet to use it in the espresso test file:

@RunWith(JUnit4::class)
class Testclass1 {

@Rule
@JvmField
val activityTestRule=
ActivityTestRule(StartupActivity::class.java, false, false)

@Before
fun setUp() {
val context = I InstrumentationRegistry.getInstrumentation().targetContext
val sharedPrefs = PreferenceManager.getDefaultSharedPreferences(context)
val editor = sharedPrefs.edit()
editor.clear()
editor.apply()
}

@Test
fun test1() {
activityTestRule.launchActivity(Intent(getInstrumentation()
.targetContext, StartupActivity::class.java))

// Rest of the test code
}
}

References:

https://developer.android.com/reference/android/content/SharedPreferences.Editor.html#clear%28%29

https://developer.android.com/reference/android/preference/PreferenceManager#getSharedPreferences()

Hope this helps.

Happy testing.

--

--