Open In App

Testing an Android Application with Example

Last Updated : 08 Apr, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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: These tests verify the behavior of individual components or modules of the app. They are usually written using JUnit and can be executed on the local machine without the need for an emulator or a physical device.
  • Integration Tests: These are tests that verify the interaction between different components or modules of the app. They are usually written using Espresso or UI Automator and require an emulator or a physical device.
  • UI Tests: These tests verify the app’s user interface, including the layout, text, images, and animations. They are usually written using Espresso or UI Automator and require an emulator or a physical device.

Testing Tools and Frameworks

  • 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 
    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.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads