How to test Activities in Android?

Testing Activities in Android is crucial for ensuring the user interface and functionality of your app are working as intended. With tools like Espresso and Robolectric, you can simulate user interactions and assert expectations on your UI components.

Example of Testing an Activity

// Gradle dependencies // Add this in your app's build.gradle file dependencies { androidTestImplementation 'androidx.test.espresso:espresso-core:3.4.0' androidTestImplementation 'androidx.test.ext:junit:1.1.3' } // Sample Test Class @RunWith(AndroidJUnit4.class) public class MainActivityTest { @Rule public ActivityTestRule activityRule = new ActivityTestRule<>(MainActivity.class); @Test public void testButtonClick() { // Check if the button is visible and click it onView(withId(R.id.my_button)).check(matches(isDisplayed())).perform(click()); // Verify the result after the button click onView(withId(R.id.result_text)).check(matches(withText("Button Clicked"))); } }

Android testing Activity testing Espresso UI testing Robolectric