Android Studio is a widely-used integrated development environment (IDE) for developing exciting mobile applications for the Android platform. Developing a mobile app on Android Studio is a great way to improve your coding and programming skills. However, the testing phase is the most critical part of the development process, as it ensures that the app is functioning correctly and meets users’ needs.
This guide will teach you how to run unit tests using Android Studio, which is an essential skill for any Android Studio developer. Running unit tests enables you to examine individual bits of code and ensure that they work as expected. These tests can help you identify and troubleshoot errors in the app’s code, enabling you to create high-quality and reliable mobile applications.
Video Tutorial:
Why You Need to Run Unit Tests on Android Studio
Before exploring how to run unit tests on Android Studio, it’s essential to understand why unit testing is critical. Here are some reasons why unit testing should be part of your app development process:
1. Debugging: The purpose of unit tests is to detect bugs in the code, allowing developers to troubleshoot them before they become problematic. This means that you can make modifications to the code before it’s deployed to the app store, increasing your app’s reliability and reducing errors in the long run.
2. Cost-Effective: Testing code that hasn’t been written is less expensive than testing written code. Investing time and effort in unit tests for each feature can accelerate development time and minimize costs.
3. Quick feedback: Unit tests give immediate feedback to developers, showing them which code works and which does not.
4. Maintainability: Consistent testing enables developers to make changes to the codebase without worrying if a previously functioning part of the application has failed.
Method 1: Using JUnit Tests
JUnit is the most standard testing framework in Java. It’s a test-driven development framework to write repeatable tests while creating new features.
Follow the detailed step-by-step guide below to set up tests used in your Android Studio project:
1. Open Android Studio
2. Create a new Android project by navigating to File → New → New Project.
3. Select an empty Activity from the group of available choices. Here, you chose "Empty Activity."
4. Now, you will find the project hierarchy on the left side. Right-click on the Java folder, then click on New → Package. Input the package name "com.company.testingtut" and hit the ‘OK’ button.
5. Create a new Java class and name it "MainActivityTest". The new class generates one method that gets the error message ‘Method not implemented." to test if the test passes.
6. Change your code to the following specifications. Details on what the code does can be found in the comments.
"`
package com.company.testingtut;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import static junit.framework.TestCase.assertEquals;
public class MainActivityTest {
/**
* Before test execution
*/
@Before
public void setUp() {
System.out.println("Before the Test");
}
/**
* During the test execution
*/
@Test
public void testAddition() {
assertEquals(4, 2 + 2);
}
/**
* After test execution
*/
@After
public void tearDown() {
System.out.println("After the Test");
}
}
"`
7. Compile and run the code by right-clicking on MainActivityTest.java and selecting "Run ".
8. When the project runs successfully, you should see a green bar on the JUnit tab, indicating that the test was successful.
Pros:
– Easy to use and set up
– Used widely in Java Development community.
– Provides immediate feedback on what’s working and what’s not
Cons:
– May not be effective in testing more profound and more complicated functions
– Cannot test computer resources such as relational databases
Method 2: Using Espresso Tests
Espresso is an open-source UI testing framework for Android Studio. Espresso tests can test the app’s user interface components and perform checks on the screen’s state.
Follow the detailed step-by-step guide below to run unit tests using Espresso:
1. Open Android Studio.
2. Create a new Android project by navigating to File → New → New Project.
3. Select an empty Activity from the available choices, then proceed with the default settings.
4. To add Espresso to your project, include the following dependencies in the build.gradle file:
"`
dependencies {
// Unit testing dependencies
testImplementation ‘junit:junit:4.12’
androidTestImplementation ‘com.android.support.test.espresso:espresso-core:3.0.2’
androidTestImplementation ‘com.android.support.test:runner:1.0.2’
androidTestImplementation ‘com.android.support:support-annotations:27.1.1’
…
}
"`
5. Once you’ve synced the Gradle files, create a new Java class named "MainActivityTest." Right-click on the test package name and select ‘New’ → ‘Java Class’ to open an empty test class file.
6. Change the MainActivityTest code to the following specifications. Details on what the code does can be found in the comments.
"`
package com.company.testingtut;
import android.support.test.rule.ActivityTestRule;
import org.junit.Rule;
import org.junit.Test;
import static android.support.test.espresso.Espresso.*;
import static android.support.test.espresso.action.ViewActions.*;
import static android.support.test.espresso.assertion.ViewAssertions.*;
import static android.support.test.espresso.matcher.ViewMatchers.*;
public class MainActivityTest {
/**
* The activity Rule provides functional testing of functional screens.
* Every rule executes when one function satisfies one equivalent requirement.
*/
@Rule
public ActivityTestRule
/**
* This function tests the addition of text by verifying that it has been added
* to the text field via Espresso’s close
*/
@Test
public void shouldAddTextToEditText() {
onView(withId(R.id.editText)).perform(typeText("Hello"), closeSoftKeyboard());
onView(withId(R.id.editText)).check(matches(withText("Hello")));
}
}
"`
7. Run the tests by right-clicking on the MainActivityTest.java file and selecting "Run".
8. If the project runs successfully, you should see a green bar on the Android Studio "Run" tab, indicating that the test was successful.
Pros:
– Espresso tests can identify application errors in real-time
– Can test the application on any device or platform
– Allows for UI-based functional testing
Cons:
– Substantial setup time is required in Android Studio
– Tests are limited to only the UI aspects of the app.
Method 3: Using Robolectric Framework
Robolectric is an open-source testing framework that enables developers to run unit tests without implementing them on physical devices.
Follow the detailed step-by-step guide below to run unit tests using Robolectric:
1. Open Android Studio.
2. Create a new Android project by navigating to File → New → New Project.
3. Select an empty Activity from the available choices, then proceed with the default settings.
4. To add Robolectric to your project, include the following dependencies in the build.gradle file:
"`
dependencies {
//Room ORM
implementation "android.arch.persistence.room:runtime:$room_version"
annotationProcessor "android.arch.persistence.room:compiler:$room_version"
//Robolectric testing framework dependency
testImplementation "org.robolectric:robolectric:4.0"
}
"`
5. Create a new Java class named "MainActivityTest." Right-click on the test package name and select ‘New’ → ‘Java Class’ to open an empty test class file.
6. Change the MainActivityTest code to the following specifications. Details on what the code does can be found in the comments.
"`
package com.company.testingtut;
import android.os.Build;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runners.RunWith;
import org.robolectric.RobolectricTestRunner;
import org.robolectric.annotation.Config;
import static junit.framework.Assert.assertEquals;
// Explicitly informs Robolectric to be aware of the AndroidTest API level sdk 28, but it’s not mandatory.
@Config(sdk = Build.VERSION_CODES.P)
@RunWith(RobolectricTestRunner.class)
public class MainActivityTest {
private MainActivity activity;
/**
* Before test execution
*/
@Before
public void setUp() {
activity = Robolectric.setupActivity(MainActivity.class);
}
/**
* During the test execution
*/
@Test
public void testAddition() {
assertEquals(4, 2 + 2);
}
/**
* After test execution
*/
@After
public void tearDown() {
activity = null;
}
}
"`
7. Run the tests by right-clicking on the MainActivityTest.java file and selecting "Run".
8. If the project runs successfully, a green bar on the Android Studio "Run" tab will indicate that the test was successful.
Pros:
– The framework provides access to a wide range of Android APIs
– Can test code that relies on the framework’s behavior
– Provides Unit tests without requiring hardware devices to run them on
Cons:
– Setup can be tricky and time-consuming
– Testing can take longer to run on large projects.
What to Do If You Can’t Run Unit Tests on Android Studio
If you can’t run the unit tests in Android Studio, something might be wrong with the way you’ve configured your project or your device is not configured correctly. Here are some possible solutions:
– Ensure that the necessary dependencies are added to the build.gradle file.
– Check that the correct Android SDK is installed. Correct it if you must.
– Verify that your test class has the @Test annotation.
– Check if the @RunWith annotation is pointing to the correct class.
– Ensure that the method names have been spelled correctly.
Bonus Tip: Integrate Continuous Integration (CI) into Your Android Studio Project
Continuous integration allows you to build, test, and deploy your code promptly. With a CI system in place, your code is always tested and ready to be merged. You can incorporate a CI system, such as Travis, CircleCI, or Jenkins, to automate your testing process.
5 FAQs About Running Unit Tests on Android Studio
Q1: Can I run my unit tests on multiple devices?
A: Yes, you can run your tests on different Android emulator devices or physical hardware devices.
Q2: Can I configure Android Studio to execute all tests automatically?
A: Yes, During the dev environment setup phase, you can configure Android Studio to run unit tests automatically whenever you build or deploy the app.
Q3: How often should I run unit tests on my project?
A: You should run unit tests whenever you make code modifications. This way, you’ll be notified right away if any of your changes have caused a regression.
Q4: What is the best type of test to use when working with Android Studio?
A: There’s no one-size-fits-all answer; each app has specific requirements. JUnit, Espresso, and Robolectric are the most popular testing frameworks, and they have different use cases.
Q5: Are unit tests the same as integration tests?
A: No, unit tests and integration tests aren’t the same. Unit tests are for individual units of code, whereas integration tests test how multiple units of code work together.
Final Thoughts
In conclusion, running unit tests on Android Studio is crucial if you want to create bug-free and reliable applications. As an Android Studio developer, you need to choose a testing framework that best suits your project’s requirements. Whether you choose JUnit, Espresso, or Robolectric, ensure that you follow the steps outlined here to help you set up your tests successfully. Remember that unit tests are an excellent way to debug your applications and are a vital component of the app development process.