Let’s create a simple scenario.
Suppose you have an Android app with a login screen. The login screen consists of two fields (username and password) and a login button. You want to test the functionality of the login process.
We’ll use the popular Android testing framework Espresso for this example.
First, make sure you have the necessary dependencies in your build.gradle file:
androidTestImplementation’ androidx.test.espresso:espresso-core:3.3.0′
androidTestImplementation’ androidx.test:runner:1.3.0′
androidTestImplementation’ androidx.test:rules:1.3.0′
Now, let’s write the test:
package com.example.myapp;
import androidx.test.espresso.Espresso;
import androidx.test.espresso.matcher.ViewMatchers;
import androidx.test.rule.ActivityTestRule;
import androidx.test.runner.AndroidJUnit4;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;
import static androidx.test.espresso.action.ViewActions.click;
import static androidx.test.espresso.action.ViewActions.typeText;
import static androidx.test.espresso.assertion.ViewAssertions.matches;
import static androidx.test.espresso.matcher.ViewMatchers.isDisplayed;
@RunWith(AndroidJUnit4.class)
public class LoginActivityTest {
@Rule
public ActivityTestRule mActivityRule = new ActivityTestRule<>(LoginActivity.class);
@Test
public void login_withValidCredentials_displaysWelcomeMessage() {
// Input username
Espresso.onView(ViewMatchers.withId(R.id.username))
.perform(typeText(“testUser”));
// Input password
Espresso.onView(ViewMatchers.withId(R.id.password))
.perform(typeText(“testPass123”));
// Click on the login button
Espresso.onView(ViewMatchers.withId(R.id.loginButton))
.perform(click());
// Check if the welcome message is displayed after a successful login
Espresso.onView(ViewMatchers.withText(“Welcome, testUser!”))
.check(matches(isDisplayed()));
}
}
Here’s a breakdown of what the code does:
- Set up: The test sets up an activity test rule for LoginActivity, which is the activity under test.
- Input username and password: The test uses Espresso to find the username and password fields by their IDs and types in test credentials.
- Click on the login button: The test then finds the loginButton and simulates a button click.
- Check welcome message: After “logging in,” the test checks to see whether a welcome message is displayed to confirm a successful login.
This is a basic example, and in real-world scenarios there would be more complexities like handling network requests, database interactions, and more. Furthermore, for actual backend authenticated tests, you’d want to mock the server response or use a dedicated testing environment to avoid altering real data.