0% found this document useful (0 votes)
153 views20 pages

Unit 04 - Testing Android Applications

Uploaded by

Google Verse
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
153 views20 pages

Unit 04 - Testing Android Applications

Uploaded by

Google Verse
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 20

UNIT 04: TESTING ANDROID APPLICATIONS

Testing an Android Application

The Android framework includes an integrated testing framework that helps you test all
aspects of your application and the SDK tools include tools for setting up and running test
applications. Whether you are working in Eclipse with ADT or working from the command
line, the SDK tools help you set up and run your tests within an emulator or the device you are
targeting.

1. Eclipse with ADT: Eclipse is an Integrated Development Environment (IDE)


commonly used for Android development. ADT (Android Development Tools) is a
plugin for Eclipse that provides tools and features specific to Android development.

2. Command line: This refers to interacting with your development environment through
text commands in a terminal or command prompt window, rather than using a graphical
interface like Eclipse.

3. SDK tools: The Android SDK (Software Development Kit) includes a set of tools that
developers use to build and test Android applications. These tools are essential for tasks
such as compiling code, debugging, and testing.

4. Set up and run your tests: This means configuring and executing tests that check the
functionality and behavior of your Android application.

5. Emulator or the device you are targeting: Android developers often test their
applications on virtual devices (emulators) or physical Android devices. The SDK tools
provide the necessary functionality to deploy and run tests on both types of devices.

Therefore, regardless of whether you prefer using Eclipse with ADT or prefer the command line
for Android development, the Android SDK tools are versatile enough to assist in configuring
and running tests on either an emulator or a physical Android device that you are developing
for. This flexibility allows developers to choose their preferred development environment while
leveraging the powerful testing capabilities provided by the SDK tools.

Test Structure

Android's build and test tools assume that test projects are organized into a standard
structure of tests, test case classes, test packages, and test projects.
• Application Packages (APKs): Application packages in Android are files with the .apk
extension that contain all the components and resources needed to run an Android
application. APKs are created from compiled code and resources and are used to
distribute and install Android applications onto devices.
• Instrumentation Test Runner: In Android, an Instrumentation Test Runner is a
component that executes and manages Android instrumentation tests. These tests are
used to validate the behavior of Android applications by interacting with the
application's UI components and APIs. The test runner executes tests on either an
emulator or a physical device.
• Test Packages: Test packages in Android contain the code and resources required for
testing an Android application. These packages include tests that are executed to verify
the functionality and behavior of the application. Test packages are often separate from
the main application package (APK) and may include unit tests, instrumentation tests,
and other types of tests.
• Instrumentation: Instrumentation in Android refers to a mechanism that allows
developers to monitor and interact with an application's behavior, usually for testing
purposes. Android instrumentation tests, as mentioned earlier, leverage this mechanism
to validate various aspects of an application by simulating user interactions and
checking outputs.
• JUnit: JUnit is a popular testing framework for Java (and Android, by extension) that
provides a framework to write and run repeatable tests. It is widely used for writing unit
tests in Android applications to verify the functionality of individual units (such as
methods or classes) of code in isolation.
• Mock Objects: Mock objects are simulated objects that mimic the behavior of real
objects in controlled ways. In testing, mock objects are often used to simulate the
behavior of complex, external components or dependencies (like databases, network
services, or sensors) that the application under test relies on. This helps isolate the code
being tested and make tests more reliable and repeatable.
• Monkey Runner: Monkey Runner is a tool provided by Android for testing
applications by generating random UI events and inputs (such as clicks, touches, and
gestures) on an emulator or device. It is primarily used for stress testing or exploring
application UI behavior under automated scenarios.

Types of Android Tests

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. Following are the different types of
testing and android application:

• 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.
JUnit is commonly used for writing and running unit tests in Android using
frameworks like Robolectric or AndroidX Test for components that require Android
framework dependencies.

• Integration Tests: These are tests that verify the interaction between different
components or modules of the app. These tests ensure that various parts of the
application work together correctly.
They are usually written using Espresso or UI Automator and require an
emulator or a physical device. Android instrumentation tests (using frameworks like
Espresso or UI Automator) are often used for integration testing to simulate user
interactions with the UI and validate the flow and behavior of the application.
• 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. Android Studio's built-in profiling tools, along with third-
party tools like Android Profiler and Firebase Performance Monitoring, can be used to
measure and analyze the performance metrics of an Android application.

Testing Tools and Frameworks

There are many tools that can be used for testing android applications. Some are official
and some are third party tools that can be used to test android applications. Following are the
different 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.
• Monkey:The UI/Application Exerciser Monkey, usually called "monkey", is a command-
line tool that sends pseudo-random streams of keystrokes, touches, and gestures to a device.
You run it with the Android Debug Bridge (adb) tool.
Publishing Android Application
• Publishing an Android application refers to the process of making an Android app
available for users to download and install on their devices via a distribution platform,
primarily the Google Play Store.
• This process involves several steps, including developing, testing, preparing, and
submitting the app to the Google Play Console, as well as ensuring it meets all
necessary guidelines and policies for distribution.
• Once published, the app can be downloaded and used by Android device users around
the world.
• In fact, publishing is the last phase of the Android application development process.
Export Android Application Process
Before exporting the apps, you must some of tools
• Dx tools(Dalvik executable tools ): It going to convert .class file to .dex file. it has
useful for memory optimization and reduce the boot-up speed time
• AAPT(Android assistance packaging tool): it has useful to convert .Dex file to.Apk
• APK(Android packaging kit): The final stage of deployment process is called as .apk.
• You will need to export your application as an APK (Android Package) file before you
upload it Google Play marketplace.

To export an application, just open that application project in Android studio and select Build
→ Generate Signed APK from your Android studio and follow the simple steps to export your
application:
Next select, Generate Signed APK option as shown in the above screen shot and then click it
so that you get following screen where you will choose Create new keystore to store your
application.

Enter your key store path,key store password,key alias and key password to protect your
application and click on Next button once again. It will display following screen to let you
create an application:
Once you filled up all the information, like app destination, build type and flavors click finish
button While creating an application it will show as below:

Finally, it will generate your Android Application as APK format File which will be uploaded
at Google Play marketplace.
Publishing an Android application involves several steps, from development to release
on the Google Play Store. Here’s are the steps involved through the process:
1. Prepare your application.
2. Create play store’s developer account.
3. Set up google play console.
4. Configure store listing.
5. Set pricing and distribution.
6. Content rating.
7. Upload app bundle or APK.
8. Review and publish.
9. Set up testing
10. Re-release app
1. Prepare Your Application:
• Build and Test: Ensure that app is fully developed and tested for bugs and
performance.
• App Bundle: Generate an Android App Bundle (.aab) or an APK (.apk) of your
application using Android Studio.
2. Create a Play store’s Developer Account:
• Sign Up: Go to the Google Play Console or any other play store and sign-up for a
developer account.
• Payment: Pay a one-time registration fee of $25(₹2085).
• Complete Profile: Fill out your developer profile with necessary information and
verify account.
3. Set Up Google Play Console:
• Login: Sign in to Google Play Console with your developer account.
• Create App: Click on "Create App" and fill in the required details such as the app's
name, default language, and app or game type.
• App Information: Provide all necessary information about your app, including the app
description, category, and contact details.
4. Configure Store Listing:
• Title and Description: Write a clear and engaging title and description for your app.
• Screenshots: Upload screenshots of your app. You can include up to 8 screenshots for
each device type (phone, tablet, Android TV, Wear OS).
• Icon and Graphics: Upload a high-resolution icon (512x512 pixels), a feature graphic
(1024x500 pixels), and, optionally a promotional video.
5. Set Pricing and Distribution:
• Pricing: Choose whether your app is free or paid. Note that you cannot change a free
app to paid later.
• Countries: Select the countries where you want to distribute your app.
• Devices: Specify if your app supports specific devices like phones, tablets, Android
TV, or Wear OS.
6. Content Rating:
• Rating Questionnaire: Complete a content rating questionnaire to determine the
appropriate rating for your app.
• Rating: The rating will be generated based on your responses and displayed on the
Play Store listing.
7. Upload App Bundle or APK:
• Upload: Go to the "Release" section and create a new release in the "Production" track.
Upload your app bundle or APK file.
• Release Notes: Add release notes for the version you are uploading, highlighting new
features or changes.
8. Review and Publish:
• Review: Double-check all the information you have provided, including the app details,
screenshots, and app bundle or APK.
• Submit: Once everything is ready, submit your app for review. Google will review
your app to ensure it meets the Play Store policies.
• Approval: The review process can take a few hours to several days. If your app meets
all the guidelines, it will be published on the Google Play Store.
9. Set Up Testing:
• Internal Testing: Invite a small group of trusted testers to provide feedback.
• Closed Testing: Expand testing to a larger group before a full release.
• Open Testing: Make the app available to a larger audience to identify any last-minute
issues.
10. Re-release app:
• After testing phase completed repeat step 7 and 8 to make sure it’s fully tested and
less/no bugs.
• After that re-release that app in ‘production’ part so that app can be accessed by public
users.
• In re-release part google play store will provide “production access” after review their
policies. This helps to reach app to public audience.

Post-Publishing Maintenance:

• Updates: Regular Updates: Ensure your app receives regular updates to address any
bugs, security vulnerabilities, and performance issues.

• New Features: Continuously add new features to enhance the user experience and keep
the app relevant.

• Compatibility: Maintain compatibility with new Android versions and devices to reach
a broader audience.

User Feedback:

• Monitor Reviews: Regularly check user reviews and ratings on the Google Play Store
to understand user sentiment.

• Feedback Integration: Integrate constructive feedback into future updates to improve


the app.

• Support: Provide timely support to users experiencing issues to maintain a positive


reputation.

Marketing:

• Promotional Campaigns: Run marketing campaigns through social media, search


engines, and other platforms to increase visibility.

• ASO (App Store Optimization): Optimize your app’s title, description, and keywords
to improve its search ranking on the Play Store.

• Engagement: Use push notifications, in-app messages, and email marketing to engage
with users and encourage them to use the app frequently.

Android preferences

Android preferences refer to the mechanism provided by the Android platform to store and
manage small amounts of application data in the form of key-value pairs. This is typically used
for saving user preferences, settings, and configuration data that should persist across
application sessions, meaning the data remains even when the application is closed and
reopened. This is done using the “SharedPreferences” class.
Shared Preferences
“SharedPreferences” is an interface for accessing and modifying preference data. It allows
storing and retrieving data as key-value pairs. The major usecases of SharedPreferences is
storing user settings (e.g., theme selection, notification preferences), application state, and
configuration data.

Steps to Use SharedPreferences

1. Getting SharedPreferences Instance:


• Use getSharedPreferences(String name, int mode) to get an instance of
SharedPreferences.
• Example: SharedPreferences sharedPreferences = getSharedPreferences("MyPrefs",
MODE_PRIVATE);
• MODE_PRIVATE is the default operating mode, meaning the created file can only be
accessed by the calling application.
2. Reading Data from SharedPreferences:
• Use methods like getString(), getInt(), getBoolean(), etc., to read data.
• Example: String username = sharedPreferences.getString("username",
"defaultName");
3. Writing Data to SharedPreferences:
• Use the Editor interface to put values into SharedPreferences.
• Example:
SharedPreferences.Editor editor =

sharedPreferences.edit();

editor.putString("username",

"JohnDoe"); editor.putInt("age", 25);


editor.apply(); // or editor.commit();

This code snippet demonstrates how to save data to SharedPreferences in an Android


application. First, it obtains an Editor instance from the SharedPreferences object using the
edit() method, which allows for making changes to the stored preferences. The putString()
method is then called on the editor to store a string value with the key "username" and the value
"JohnDoe". Similarly, the putInt() method is used to store an integer value with the key "age"
and the value 25. Finally, the apply() method is invoked to asynchronously save these changes
to the SharedPreferences. Alternatively, the commit() method can be used to synchronously
save the changes, which blocks until the changes are written to persistent storage and returns a
boolean indicating success. The apply() method is generally preferred for performance reasons,
as it performs the save operation in the background without blocking the main thread.

Benefits of Using SharedPreferences

• Persistence: Data stored in SharedPreferences persists across app sessions.


• Simplicity: Easy to use for storing simple data.
• Performance: Efficient for small amounts of data.
• Security: Can be made private to the application.

Real-Time Example: A Simple Settings Screen

Let's consider a real-time example where an Android application has a settings screen that
allows users to toggle notifications on and off and to select a theme (light or dark mode).
These preferences need to be saved and retrieved even after the app is closed and reopened.

Step-by-Step Implementation

1. Create a Layout File (res/layout/activity_settings.xml)

<?xml version="1.0" encoding="utf-8"?>


<LinearLayout
xmlns:android="http://schemas.android.com/apk/res
/android"

android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="16dp">
<Switch

android:id="@+id/switchNotifications"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Enable Notifications" />

<RadioGroup
android:id="@+id/radioGroupTheme"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">

<RadioButton
android:id="@+id/radioLight"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Light Theme" />

<RadioButton
android:id="@+id/radioDark"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Dark Theme" />
</RadioGroup>

<Button
android:id="@+id/btnSave"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Save" />
</LinearLayout>
2. Settings Activity (SettingsActivity.java)
package com.example.preferencesexample;
import android.content.SharedPreferences;

import android.os.Bundle;
import android.widget.Button; import
android.widget.RadioButton;import
android.widget.RadioGroup; import android.widget.Switch;
import androidx.appcompat.app.AppCompatActivity;
public class SettingsActivity extends AppCompatActivity
public class SettingsActivity extends AppCompatActivity {
private Switch switchNotifications;
private RadioGroup radioGroupTheme; private
RadioButton radioLight, radioDark;private Button
btnSave;
private static final String PREFS_NAME =
"AppSettingsPrefs";
private static final String KEY_NOTIFICATIONS =
"notifications";
private static final String KEY_THEME = "theme";

@Override
protected void onCreate(Bundle savedInstanceState)

super.onCreate(savedInstanceState);
setContentView(R.layout.activity_settings);

switchNotifications =
findViewById(R.id.switchNotifications);
radioGroupTheme =
findViewById(R.id.radioGroupTheme);
radioLight = findViewById(R.id.radioLight);
radioDark = findViewById(R.id.radioDark);
btnSave = findViewById(R.id.btnSave);

loadPreferences();

btnSave.setOnClickListener(v ->savePreferences());
private void savePreferences()
{
SharedPreferences sharedPreferences =
getSharedPreferences(PREFS_NAME, MODE_PRIVATE);
SharedPreferences.Editor editor =
sharedPreferences.edit();

boolean notificationsEnabled =
switchNotifications.isChecked();
int selectedTheme =
radioGroupTheme.getCheckedRadioButtonId() ==
R.id.radioLight ? 0 : 1;
editor.putBoolean(KEY_NOTIFICATIONS,
notificationsEnabled);
editor.putInt(KEY_THEME, selectedTheme);
editor.apply();
}
private void loadPreferences() { SharedPreferences
sharedPreferences =
getSharedPreferences(PREFS_NAME, MODE_PRIVATE);

boolean notificationsEnabled =
sharedPreferences.getBoolean(KEY_NOTIFICATIONS, false);
int selectedTheme =
sharedPreferences.getInt(KEY_THEME, 0);

switchNotifications.setChecked(notificationsEnabled);

if (selectedTheme == 0)

radioLight.setChecked(true);

}
else {
radioDark.setChecked(true);
}
}
}

1. Layout: The layout file contains a Switch for enabling/disabling notifications, a


RadioGroup with RadioButtons for selecting the theme, and a Button to save the settings.
2. SettingsActivity:

• onCreate(): Initializes the UI components, loads the saved preferences, and sets a click
listener for the save button.
• savePreferences(): Retrieves the current states of the Switch and RadioGroup, and
saves them to SharedPreferences using an Editor.
• loadPreferences(): Retrieves the saved preferences from SharedPreferences and sets
the UI components to reflect these saved states.

Running the Example

When you run the example:

1. Open the settings screen.


2. Toggle the notifications switch and select a theme.
3. Press the save button.
4. Close and reopen the app.
5. Open the settings screen again. The preferences will be loaded and the UI components
will reflect the saved states.

This example demonstrates how SharedPreferences can be used to persist user settings in an
Android application, providing a consistent and personalized user experience across app
sessions.
Managing Application resources in a hierarchy

Managing application resources in a hierarchy is a fundamental practice in Android


development that helps in organizing resources like layouts, strings, images, and styles
efficiently. This hierarchical structure allows the application to adapt to various device
configurations, such as different screen sizes, languages, and orientations.

There are many more items which you use to build a good Android application. Apart from
coding for the application, you take care of various other resources like static content that your
code uses, such as bitmaps, colors, layout definitions, user interface strings, animation
instructions, and more. These resources are always maintained separately in various sub-
directories under res/ directory of the project.
Following are some of the directories and resource types:drawable/: Image files like .png, .jpg,
.gif or XML files that are compiled into bitmaps, state lists, shapes, animation drawable. They
are saved in res/drawable/ andaccessed from the R.drawable class.
• anim/: XML files that define property animations. They are saved in res/anim/ folder and
accessed from the R.anim class.
• color/: XML files that define a state list of colors. They are saved in res/color/ and accessed
from the R.color class.
• layout/: XML files that define a user interface layout. They are saved in res/layout/ and
accessed from the R.layout class.
• menu/: XML files that define application menus, such as an Options Menu, Context Menu,
or Sub Menu. They are saved in res/menu/ and accessed from the R.menu class.
• raw/: Arbitrary files to save in their raw form. You need to call
Resources.openRawResource() with the resource ID, which is R.raw.filename to open such
raw files.
• values/: XML files that contain simple values, such as strings, integers, and colors. For
example, here are some filename conventions for resources you can create in this directory –
❖ arrays.xml for resource arrays, and accessed from the R.array class.

❖ integers.xml for resource integers, and accessed from the R.integer class.

❖ bools.xml for resource boolean, and accessed from the R.bool class.

❖ colors.xml for color values, and accessed from the R.color class.

❖ dimens.xml for dimension values, and accessed from the R.dimen class.

❖ strings.xml for string values, and accessed from the R.string class.

❖ styles.xml for styles, and accessed from the R.style class.

• xml/: Arbitrary XML files that can be read at runtime by calling


Resources.getXML(). You can save various configuration files here which will be
used at run time.

Alternative Resources
Your application should provide alternative resources to support specific device
configurations. For example, you should include alternative drawable resources (i.e. Images) for
different screen resolution and alternative string resources for different languages. At runtime,
Android detects the current device configuration and loads the appropriate resources for your
application.
To specify configuration-specific alternatives for a set of resources, follow the following steps:
• Create a new directory in res/ named in the form
<resources_name>-<config_qualifier>.
• Here resources_name will be any of the resources mentioned in the above table, like
layout, drawable etc. The qualifier will specify an individual configuration for which
these resources are to be used. You can check official documentation for a complete list
of qualifiers for different type of resources.
• Save the respective alternative resources in this new directory. The resource files must
be named exactly the same as the default resource files as shown in the below example,
but these files will have content specific to the alternative. For example, though image
file name will be same but for high resolution screen, its resolution will be high.
Below is an example which specifies images for a default screen and alternative images for high
screen resolution screen.
Working with different types of resources / Accessing Resources
During your application development you will need to access defined resources either
in your code, or in your layout XML files. Following section explains how to access your
resources inboth the scenarios −
• Accessing Resources in Code
• Accessing Resources in XML

Accessing Resources in Code

When your Android application is compiled, a R class gets generated, which contains resource
IDs for all the resources available in your res/ directory. You can use R class to access that
resource using sub-directory and resource name or directly resource ID.

Example: To access res/drawable/myimage.png and set an ImageView you will use following
code −

ImageView imageView = (ImageView)


findViewById(R.id.myimageview);

imageView.setImageResource(R.drawable.myimage);

Here first line of the code make use of R.id.myimageview to get ImageView defined with id
myimageview in a Layout file. Second line of code makes use of R.drawable.myimage to get
an image with name myimage available in drawable sub-directory under /res.

Example: Consider next example where res/values/strings.xml has following definition −


<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="hello">Hello, World!</string>
</resources>
Now you can set the text on a TextView object with ID msg using a resource ID as follows −
TextView msgTextView = (TextView) findViewById(R.id.msg);
msgTextView.setText(R.string.hello);
Example: Consider a layout res/layout/activity_main.xml with the following definition −

<?xml version="1.0" encoding="utf-8"?>

<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"

android:layout_width="fill_parent"
android:layout_height="fill_parent"

android:orientation="vertical" >

<TextView android:id="@+id/text"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Hello, I am a TextView" />

<Button android:id="@+id/button"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Hello, I am a Button" />

</LinearLayout>

This application code will load this layout for an Activity, in the onCreate() method as
follows −

public void onCreate(Bundle savedInstanceState)

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

Accessing Resources in XML


Consider the following resource XML res/values/strings.xml file that includes a color
resource and a string resource −

<?xml version="1.0" encoding="utf-8"?>

<resources>

<color name="opaque_red">#f00</color>

<string name="hello">Hello!</string>

</resources>

Now you can use these resources in the following layout file to set the text color and text
string as follows −

<?xml version="1.0" encoding="utf-8"?>

<EditText
xmlns:android="http://schemas.android.com/apk/res/android"

android:layout_width="fill_parent"

android:layout_height="fill_parent"

android:textColor="@color/opaque_red"

android:text="@string/hello" />

Now if you will go through previous chapter once again where I have explained Hello World!
example, and I'm sure you will have better understanding on all the concepts explained in this
chapter. So I highly recommend to check previous chapter for working example and check
how I have us

You might also like