অন্তহীন ছুটে চলা, অবিরাম জীবনের অর্থ খুজে ফেরা

Android: Instrumentation Testing using Espresso

Introduction

Android provides a number of extra components beyond Java, for example, Activity, Service etc. Testing these extra components you will be required Instrumentation testing and it needs to be run on device/emulators. Espresso is an official instrumentation testing framework by Google.

@RunWith(AndroidJUnit4.class)
public class MainActivityTest {
// This will launch the MainActivity before testing each method/case.
@Rule
public ActivityTestRule<MainActivity> activityTestRule = new ActivityTestRule<>(MainActivity.class);
@Test
public void testCase1() {
// Find a view with id = R.id.text
// Check the text of that view matches with string = R.string.app_name
onView(withId(R.id.text)).check(matches(withText(R.string.app_name)));
}
}

Now Right click on the file MainActivityTest.java from project explorer and select “Create MainActivityTest…” -> OK.
Click on Run.

Now we will add our second test case

@Test
public void testCase2() {
// Open options menu, whether as overflow or using a physical button
// This will open the option menu as a pop up menu. Next we will click on an item.
// If you need context then pass, InstrumentationRegistry.getTargetContext()
openActionBarOverflowOrOptionsMenu(InstrumentationRegistry.getTargetContext());
// From the options menu, we are going to click on an item having text = R.string.label_help
onView(withText(R.string.label_help)).perform(click());
// alternatively, you can leverage id property.
onView(withId(R.id.menu_help)).perform(click());
// verifying
onView(withId(R.id.text)).check(matches(withText(R.string.label_updated)));
}