Clear Shared Preferences In Android Espresso Tests — Kotlin

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:

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.

3. Clearing Shared preferences from default :

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

Code snippet to use it in the espresso test file:

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.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store