How to Set Shared Preferences in Espresso Test for Kotlin and Java

I have experienced Espresso and needed to deep dive into Shared Preferences
just because it is one of the main parameters used in the application we developed. As a long search in the online sources but there are some pretty old documents for Espresso with Java and very few documents about Espresso with Kotlin. In this post, I want to share my experiences with setting Shared Preferences with Kotlin and Java and how you can use it in your test design. You can follow up the steps for your test project.

Shared Preferences is a way to store user data in local devices so it has been supported since the very early version of Android. Shared Preferences can be stored in the default file or custom file. 

Using Default File for Shared Preferences

If your application uses the default file it should stores the shared data in the default file provide by Android as in the following path in the device:
This is the source code for getDefaultSharedPreferencesName

For this case, you can set/clear/get shared preferences by the following method:

Using Customized File for Shared Preferences

The same way. your application can use a custom file to store shared preferences. This time you need to get the name of the .xml file for storing shared preferences. You can find the file in the same path with the default preference file. If the file name is `MyAppSharedPreferences`, the file path should be like the following:
For this case, you can set/clear/get shared preferences by the following method:

When there is an update in shared preference/application data,  we need to launch the application after this update. To do this, launchActivity should be set to false during initialization.

See the full code in Kotlin:
See the full code in Java:


Popular posts from this blog

Testing WEB Sevices and Automating SOAP Services

Performance Testing on CI: Locust is running on Jenkins

Change Default Timeout and Wait Time of Capybara

Performance Testing on CI: Integration of Locust and Jenkins

Create an Alias for Interactive Console Work: Selenium and Capybara