Make your Android app releases airtight with Espresso for regression testing
Tags: android, beginners, tutorial, espresso
Published: 2022-02-11 18:59:57

Often while working as a Developer we are struck with problems that need more than usual attention.
During such situations, my seniors would help me, but we were using espresso for the first time and so I had to help myself.
By the way, Anubhav here, with a little guide to make you sail the journey easily.

## Goal.
Setting shared preference before starting the activity during Espresso Testing.

## Why?
In our android application, during onboarding the users save a few selected items, and based on them we fetch the contents for them.

While performing instrumentation test( just fancy name for saying UI tests) in android we need to set the preferences otherwise we would be shown a Dialog box saying no item selected and the test would fail.


## Solution
![solution in Image form](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/x5ivuwaa94reirhymys9.png)
 
### 1. Using Activity Test Rule 
> Rules are used to add additional functionality which applies to all tests within a test class, but more generically.

if we are using the Activity test rule we can very easily support setting shared preference.

As we can initialize the activity but not start it. This is very <B> important </B> for us as we want to set the shared preferences before the activity could start.

```
@Rule
public ActivityTestRule<MainActivity> mActivityRule = new ActivityTestRule<>(
            MainActivity.class,
            true,
            false); 
```
Here the three parameter's passed to the function are 
 * Activity test class
 * Initial touch mode
 * Launch Activity

 Since we have set the <B>Launch Activity</B> to false, the activity would be initialized but not launched and in the meantime, we could set up our shared preferences.

 ```
@Before
fun setUp(){
val prefs: SharedPreferences = PreferenceManager.getDefaultSharedPreferences(
          getInstrumentation().targetContext
        )
      val editor = prefs.edit()
      editor.clear().apply()
 }
```

And then we can start the activity at our will.

```
    @Test
    fun populateUsernameFromSharedPrefsTest() {
   
        // Launch activity
        mActivityRule.launchActivity(new Intent())

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

```

But this function is Deprecated and hence I was looking for better options.

### 2. Using Activity Scenario Rule
Basic stuff: Activity Scenario unifies managing lifecycle in <U> Android Test support library</U> and <U> Robolelectric </U> and is a Part of Android X Test Library.

1. Use LazyActivityScenarioRule
2. Use Chaining Rules

### Lazy Activity Scenario Rule 
[Medium Article for reference](https://medium.com/stepstone-tech/better-tests-with-androidxs-activityscenario-in-kotlin-part-1-6a6376b713ea)

I did not got chance to test this out but it looks quite promising to me. do checkout the blog.

### Chaining Rules

Using chaining rules is as simple as 

```
@Rule
fun chain(): TestRule = RuleChain.outerRule(EspressoSharedPreferenceSetupRule()).around(ActivityScenarioRule(MainActivity::class.java))  
```
Here <b> EspressoSharedPreferenceSetupRule </b> is a simple test Rule class.

```
class EspressoSharedPreferenceSetupRule : TestRule {
  override fun apply(base: Statement?, description: Description?): Statement? {
    val prefs: SharedPreferences = PreferenceManager.getDefaultSharedPreferences(
        InstrumentationRegistry.getInstrumentation().targetContext
      )
    val editor = prefs.edit()
    editor.clear().apply()

    // do something here
    
    )
    editor.apply()
    return base
  }
}
```

### What is happening here. (Magic)

![Chaining](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/zqjjewp5e6nv2oxqpnyn.png)
 

There are two rules defined.
1. <B> Activity Scenario Rule</B>
2. <B> Espresso Shared Preference Rule </B>


The <B> outer rules </B> are configured to be run first and then the <B> inside one </B> works and this is how we have chained them. 

Hence it guarantees that our Espresso Shared Preference is run first and then our activity is launched.



> Feel Free to connect with me or comment down below If you found this interesting.