Testing an Android Application with Example

Testing is an essential part of the Android app development process. It helps to ensure that the app works as expected, is bug-free, and provides a seamless user experience. Android offers various testing tools and frameworks that can be used to write and execute different types of tests, including unit tests, integration tests, and UI tests.

Types of Android Tests

  • Unit Tests:
    • Unit tests are automated and are run each time the code is changed to ensure that new code does not break existing functionality.
    • Run multiple tests at once to find and fix problems faster.
    • Test on real Android devices to ensure your app works perfectly on real hardware.
  • Integration Tests:
    • Integration testing is testing the interface between two software units or modules. It focuses on determining the correctness of the interface.
    • Integration testing is a software testing technique that focuses on verifying the interactions and data exchange between different components or modules of a software application.
    • Work with your team in real time while testing your app on real devices, discussing issues as you see them.
  • UI Tests:
    • Make sure your app looks and works great on all screen sizes and devices
    • Automatically check if your app’s design stays consistent even after changes
    • Test your app for accessibility, making sure everyone can use it easily.

Testing Tools and Frameworks

  • LambdaTest: It is an AI-powered test orchestration and execution platform that allows you to run Android app tests on an online device farm of real and virtual Android smartphones. You can automate Android tests with mobile app testing frameworks like Appium and Espresso across different Android devices and their OS versions.
  • JUnit: This is a popular testing framework for Java that can be used to write unit tests for Android apps.
  • Espresso: This is a testing framework for Android that can be used to write UI tests for apps. It provides a fluent API for interacting with UI components and verifying their behavior.
  • UI Automator: This is another testing framework for Android that can be used to write UI tests. It provides a set of APIs for interacting with UI components and verifying their behavior.
  • Robolectric: This is a testing framework for Android that can be used to write unit tests for Android apps. It allows developers to run tests on the local machine without the need for an emulator or a physical device.
  • Mockito: This is a mocking framework for Java that can be used to create mock objects for unit testing.

Step-by-Step Implementation

Step 1: Create a New Project in Android Studio

Here is an example of an Android app that includes a simple calculator feature, and includes a unit test to verify that the calculator is functioning correctly. To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. The code for that has been given in Kotlin Programming Language for Android.

Step 2: Working with the activity_main.xml file

Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file. Comments are added inside the code to understand the code in more detail.

XML
<LinearLayout 
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <TextView
        android:id="@+id/result"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:textSize="50sp" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <Button
            android:id="@+id/button_one"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="1" />

        <Button
            android:id="@+id/button_two"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="2" />

        <Button
            android:id="@+id/button_plus"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="+" />
      
    </LinearLayout>
  
</LinearLayout>

Step 3: Working with the MainActivity File

Go to the MainActivity File and refer to the following code. Since there is no change in MainActivity File, keep it as it is. This code sets up the UI elements and adds listeners to the Buttons. When a Button is clicked, it calls a method to add a number or operation to the TextView. The calculation method will eventually perform the actual calculations.

Java
import android.os.Bundle;
import android.widget.Button;
import android.widget.TextView;
import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

    private TextView result;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        result = findViewById(R.id.result);
        Button buttonOne = findViewById(R.id.button_one);
        Button buttonTwo = findViewById(R.id.button_two);
        Button buttonPlus = findViewById(R.id.button_plus);

        buttonOne.setOnClickListener(view -> addNumber(1));
        buttonTwo.setOnClickListener(view -> addNumber(2));
        buttonPlus.setOnClickListener(view -> addOperation());
    }

    private void addNumber(int number) {
        String currentText = result.getText().toString();
        result.setText(currentText + number);
    }

    private void addOperation() {
        String currentText = result.getText().toString();
        result.setText(currentText + "+");
    }

    public int calculate(String expression) {
        String[] parts = expression.split("\\+");
        int sum = 0;
        for (String part : parts) {
            sum += Integer.parseInt(part);
        }
        return sum;
    }
}
Kotlin
import android.os.Bundle
import android.widget.Button
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity

class MainActivity : AppCompatActivity() {

    private lateinit var result: TextView

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        
        result = findViewById(R.id.result)

        val buttonOne = findViewById<Button>(R.id.button_one)
        val buttonTwo = findViewById<Button>(R.id.button_two)
        val buttonPlus = findViewById<Button>(R.id.button_plus)

        buttonOne.setOnClickListener { addNumber(1) }
        buttonTwo.setOnClickListener { addNumber(2) }
        buttonPlus.setOnClickListener { addOperation() }
    }

    private fun addNumber(number: Int) {
        val currentText = result.text.toString()
        result.text = currentText + number
    }

    private fun addOperation() {
        val currentText = result.text.toString()
        result.text = "$currentText+"
    }

    fun calculate(expression: String): Int {
        val parts = expression.split("\\+".toRegex()).toTypedArray()
        var sum = 0
        for (part in parts) {
            sum += part.toInt()
        }
        return sum
    }
}

Step 4: Working with the MainActivity Unit Testing File

Finally, we can create a unit test for the calculation method.

Java
import static org.junit.Assert.assertEquals;
import androidx.test.ext.junit.runners.AndroidJUnit4;
import org.junit.Test;
import org.junit.runner.RunWith;

@RunWith(AndroidJUnit4.class)
public class ExampleInstrumentedTest {

    @Test
    public void testCalculate() {
        MainActivity activity = new MainActivity();
        int result = activity.calculate("1+2");
        assertEquals(3, result);
    }
}
Kotlin
import androidx.test.ext.junit.runners.AndroidJUnit4
import org.junit.Assert
import org.junit.Test
import org.junit.runner.RunWith

@RunWith(AndroidJUnit4::class)
class ExampleInstrumentedTest {
  
    @Test
    fun testCalculate() {
        val activity = MainActivity()
        val result: Int = activity.calculate("1+2")
        Assert.assertEquals(3, result.toLong())
    }
}

Output:

Android testing is an essential part of the app development process. It helps to ensure that the app works as expected, is bug-free, and provides a seamless user experience. There are various testing tools and frameworks available for Android, including JUnit, Espresso, UI Automator, Robolectric, and Mockito. By following best practices for Android testing, developers can write tests that are effective, efficient, and maintainable.



Contact Us