Professional Documents
Culture Documents
This page includes instructions for basic debugger operations. For more documentation,
also see the IntelliJ IDEA debugging docs.
1. Enable debugging
Before you can begin debugging, you need to prepare as follows:
Install LLDB:
If your project includes C/C++ code, you need to install LLDB from the SDK Manager.
Enable debugging on your device:
If you're using the emulator, this is enabled by default. But for a connected device, you
need to enable debugging in the device developer options.
Run a debuggable build variant:
You must use a build variant that includes debuggable true in the build configuration.
Usually, you can just select the default "debug" variant that's included in every Android
Studio project (even though it's not visible in the build.gradle file). But if you define
new build types that should be debuggable, you must add `debuggable true` to the build
type:
android {
buildTypes {
customDebugType {
debuggable true
...
}
}
}
This property also applies to modules with C/C++ code. (The jniDebuggable property
is no longer used.)
Note: If your app depends on a library module that you also want to debug, that library must also be
packaged with debuggable true so it retains its debug symbols. To ensure that the debuggable
variants of your app project receive the debuggable variant of a library module, be sure that
you publish non-default versions of your library.
2. Start debugging
You can start a debugging session as follows:
2. In the toolbar, click Debug to display the Select Deployment Target window.
If no devices appear in the Select Deployment Target window after you click Debug,
then you need to eitherconnect a device via USB or click Create new virtual device to
use the Android Emulator.
If, instead of the Select Deployment Target window, you see a dialog asking if you
want to "switch from Run to Debug," that means your app is already running on the
device and it will restart in order to begin debugging. If you'd rather keep the same
instance of the app running, click Cancel Debug and instead attach the debugger to a
running app.
3. Select a deployment target and click OK.
Android Studio builds an APK, signs it with a debug key, installs it on your selected
device, and runs it. If youadd C and C++ code to your project, Android Studio also runs
the LLDB debugger in the Debug window to debug your native code.
4. If the Debug window is not open, select View > Tool Windows > Debug (or
click Debug in the tool window bar), and then click the Debugger tab, as shown in
figure 1.
Figure 1. The Debugger window, showing the current thread and the object tree for a variable
Auto: Select if you want Android Studio to automatically choose the best option for the
code you are debugging. For example, if you have any C or C++ code in your project,
Android Studio automatically uses the Dual debug type. Otherwise, Android Studio uses
the Java debug type.
Java: Select if you want to debug only code written in Java or Kotlin—the Java
debugger ignores any breakpoints or watches you set in your native code.
Native: (Available only with C/C++ code.) Select if you want to use only LLDB to debug
your code. When using this debug type, the Java debugger session view is not
available. By default, LLDB inspects only your native code and ignores breakpoints in
your Java code. If you want to also debug your Java code, you should switch to either
the Auto or Dual debug type.
Note: Native debugging does not work on 32-bit Windows in Android Studio 3.0 and higher. If you
are using 32-bit Windows and you need to debug native code, you should use Android Studio 2.3.
Dual: (Available only with C/C++ code.) Select if you want to switch between debugging
both Java and native code. Android Studio attaches both the Java debugger and LLDB
to your app process, one for the Java debugger and one for LLDB, so you can inspect
breakpoints in both your Java and native code without restarting your app or changing
your debug configuration.
In figure 2, notice the two tabs to the right of the Debug window title. Because the app
has both Java and C++ code, one tab is for debugging the native code, and the other
for debugging Java code, as indicated by -java.
Figure 2. Tab for debugging native code and tab for debugging Java code
Note: If you are debugging native code that is optimized by the compiler, you may get the following
warning message: This function was compiled with optimizations enabled. Some
debugger features may not be available. When using optimization flags, such as -O flags, the
compiler makes changes to your compiled code to make it run more efficiently. This can cause the
debugger to report unexpected or incorrect information because it’s difficult for the debugger to map
the optimized compiled code back to the original source code. For this reason, you should disable
compiler optimizations while debugging your native code.
The following example shows how you might add log messages to determine if previous
state information is available when your activity starts:
KOTLINJAVA
import android.util.Log
...
private val TAG: String = MyActivity::class.java.simpleName
...
class MyActivity : Activity() {
...
override fun onCreate(savedInstanceState: Bundle?) {
...
if (savedInstanceState != null) {
Log.d(TAG, "onCreate() Restoring previous state")
/* restore state */
} else {
Log.d(TAG, "onCreate() No saved state available")
/* initialize app */
}
}
}
During development, your code can also catch exceptions and write the stack trace to
the system log:
KOTLINJAVA
fun someOtherMethod() {
try {
...
} catch (e : SomeException) {
Log.d(TAG, "someOtherMethod()", e)
}
}
Note: Remove debug log messages and stack trace print calls from your code when you are ready
to publish your app. You could do this by setting a DEBUG flag and placing debug log messages
inside conditional statements.
To use logcat, start debugging and select the Logcat tab in the bottom toolbar as
shown in figure 3.
For a description of logcat and its filtering options, see Write and view logs with Logcat.
1. Locate the line of code where you want to pause execution, then either click the left
gutter along that line of code or place the caret on the line and press Control+F8 (on
Mac, Command+F8).
2. If your app is already running, you don't need to update it to add the breakpoint—just
clicking Debug .
Figure 3. A red dot appears next to the line when you set a breakpoint
When your code execution reaches the breakpoint, Android Studio pauses execution of
your app. You can then use the tools in the Debugger tab to identify the state of the
app:
To examine the object tree for a variable, expand it in the Variables view. If
the Variables view is not visible, click Restore Variables View .
To evaluate an expression at the current execution point, click Evaluate
Expression .
To advance to the next line in the code (without entering a method), click Step
Over .
To advance to the first line inside a method call, click Step Into .
To advance to the next line outside the current method, click Step Out .
To continue running the app normally, click Resume Program .
If your project uses any native code, by default the Auto debug type attaches both the
Java debugger and LLDB to your app as two separate processes, so you can switch
between inspecting Java and C/C++ breakpoints without restarting your app or
changing settings.
Note: For Android Studio to detect breakpoints in your C or C++ code, you need to use a debug type
that supports LLDB, such as Auto, Native, or Dual. You can change the debug type Android Studio
uses by editing your debug configuration. To learn more about the different debug types, read the
section about using other debug types.
When Android Studio deploys your app to your target device, the Debug window opens
with a tab or debug session view for each debugger process, as shown in figure 4.
While debugging C/C++ code, you can also set special types of breakpoints,
called watchpoints, that can suspend your app process when your app interacts with a
particular block of memory. To learn more, read the section about how to add
watchpoints.
Figure 5. The Breakpoints window lists all the current breakpoints and includes behavior settings for
each
The Breakpoints window lets you enable or disable each breakpoint from the list on the
left. If a breakpoint is disabled, Android Studio does not pause your app when it hits that
breakpoint. Select a breakpoint from the list to configure its settings. You can configure
a breakpoint to be disabled at first and have the system enable it after a different
breakpoint is hit. You can also configure whether a breakpoint should be disabled after
it is hit. To set a breakpoint for any exception, select Exception Breakpoints in the list
of breakpoints.
The Watches pane provides similar functionality except that expressions added to
the Watches pane persist between debugging sessions. You should add watches for
variables and fields that you access frequently or that provide state that is helpful for the
current debugging session. The Variables and Watches panes appear as shown in
figure 5.
1. Begin debugging.
To remove an item from the Watches list, select the item and then click Remove .
You can reorder the elements in the Watches list by selecting an item and then
clicking Up or Down .
In Android Studio, you can create a watchpoint during runtime by selecting a specific
variable, but LLDB assigns the watchpoint to only the block of memory the system
allocates to that variable, not the variable itself. This is different from adding a variable
to the Watches pane, which enables you to observe the value of a variable but doesn’t
allow you to suspend your app process when the system reads or changes its value in
memory.
Note: When your app process exits a function and the system deallocates its local variables from
memory, you need to reassign any watchpoints you created for those variables.
Your target physical device or emulator uses an x86 or x86_64 CPU. If your device
uses an ARM CPU, then you must align the boundary of your variable’s address in
memory to either 4 bytes for 32-bit processors, or 8 bytes for 64-bit processors. You can
align a variable in your native code by
specifying __attribute__((aligned(num_bytes))) in the variable deceleration, as
shown below:
// For a 64-bit ARM processor
int my_counter __attribute__((aligned(8)));
You have assigned three or fewer watchpoints already. Android Studio only supports up
to four watchpoints on x86 or x86_64 target devices. Other devices may support fewer
watchpoints.
If you meet the requirements above, you can add a watchpoint as follows:
1. While your app is suspended on a breakpoint, navigate to the Variables pane in your
LLDB session view.
2. Right-click on a variable that occupies the block of memory you want to track and
select Add Watchpoint. A dialog to configure your watchpoint appears, as shown in
figure 7.
Figure 7. Adding a watchpoint to a variable in memory
3. Configure your watchpoint with the following options:
Enabled: You can deselect this option if you want to tell Android Studio to ignore the
watchpoint for the time being. Android Studio still saves your watchpoint so you can
access it later in your debug session.
Suspend: By default, the Android system suspends your app process when it accesses
a block of memory you assign to a watchpoint. You can deselect this option if you don’t
want this behavior—this reveals additional options you can use to customize behavior
when the system interacts with your watchpoint: Log message to
console and Remove [the watchpoint] when hit.
Access Type: Select whether your app should trigger your watchpoint when it tries
to Read or Write to the block of memory the system allocates to the variable. To trigger
your watchpoint on either a read or write, select Any.
4. Click Done.
To view all your watchpoints and configure watchpoint settings, click View
Breakpoints on the left side of the Debug window. The Breakpoints dialog
appears, as shown in figure 8.
Figure 8. The Breakpoints dialogue lists your current watchpoints and includes behavior settings for
each
After you add your watchpoint, click Resume Program on the left side of
the Debug window to resume your app process. By default, if your app tries to access a
block of memory that you have set a watchpoint to, the Android system suspends your
app process and a watchpoint icon appears next to the line of code that your app
executed last, as shown in figure 9.
Figure 9. Android Studio indicates the line of code that your app executes just before triggering a
watchpoint
7. View and change resource value display format
In debug mode, you can view resource values and select a different display format for
variables in your Java code. With the Variables tab displayed and a frame selected, do
the following:
1. In the Variables list, right-click anywhere on a resource line to display the drop-down
list.
2. In the drop-down list, select View as and select the format you want to use.
The available formats depend on the data type of the resource you selected. You might
see any one or more of the following options:
Class: Display the class definition.
toString: Display string format.
Object: Display the object (an instance of a class) definition.
Array: Display in an array format.
Timestamp: Display date and time as follows: yyyy-mm-dd hh:mm:ss.
Auto: Android Studio chooses the best format based on the data type.
Binary: Display a binary value using zeroes and ones.
MeasureSpec: The value passed from the parent to the selected child.
See MeasureSpec.
Hex: Display as a hexadecimal value.
Primitive: Display as a numeric value using a primitive data type.
Integer: Display a numeric value of type Integer.
Set up your Android device for remote debugging, and discover it from your development
machine.
Inspect and debug live content on your Android device from your development machine.
Screencast content from your Android device onto a DevTools instance on your development
machine.
Figure 1. Remote Debugging lets you inspect a page running on an Android device from your
development machine.
1. Step 1: Discover your Android device
The workflow below works for most users. See Troubleshooting: DevTools is not
detecting the Android device for more help.
1. Open the Developer Options screen on your Android. See Configure On-Device Developer
Options.
2. Select Enable USB Debugging.
3. On your development machine, open Chrome.
4. Open DevTools.
5. In DevTools, click the Main Menu then select More tools > Remote devices.
Figure 2. Opening the Remote Devices tab via the Main Menu
8. Connect your Android device directly to your development machine using a USB cable.
The first time you do this, you usually see that DevTools has detected an unknown
device. If you see a green dot and the text Connected below the model name of your
Android device, then DevTools has successfully established the connection to your
device. Continue to Step 2.
Figure 4. The Remote Devices tab has successfully detected an unknown device that is
pending authorization
If you're using a USB hub, try connecting your Android device directly to your development
machine instead.
Try unplugging the USB cable between your Android device and development machine, and
then plugging it back in. Do it while your Android and development machine screens are
unlocked.
Make sure that your USB cable works. You should be able to inspect files on your Android
device from your development machine.
If you don't see the Allow USB Debugging prompt on your Android device try:
Disconnecting and then re-connecting the USB cable while DevTools is in focus on your
development machine and your Android homescreen is showing. In other words, sometimes the
prompt doesn't show up when your Android or development machine screens are locked.
Updating the display settings for your Android device and development machine so that they
never go to sleep.
Setting Android's USB mode to PTP. See Galaxy S4 does not show Authorize USB debugging
dialog box.
Select Revoke USB Debugging Authorizations from the Developer Options screen on your
Android device to reset it to a fresh state.
If you find a solution that is not mentioned in this section or in Chrome DevTools
Devices does not detect device when plugged in, please add an answer to that Stack
Overflow question, or open an issue in the webfundamentals repository!
3. In the New tab text box, enter a URL and then click Open. The page opens in a new
tab on your Android device.
4. Click Inspect next to the URL that you just opened. A new DevTools instance opens.
The version of Chrome running on your Android device determines the version of
DevTools that opens on your development machine. So, if your Android device is
running a very old version of Chrome, the DevTools instance may look very different
than what you're used to.
Inspect elements
Go to the Elements panel of your DevTools instance, and hover over an element to
highlight it in the viewport of your Android device.
You can also tap an element on your Android device screen to select it in
the Elements panel. Click Select Element on your DevTools instance, and then
tap the element on your Android device screen. Note that Select Element is disabled
after the first touch, so you need to re-enable it every time you want to use this feature.
Click Toggle Screencast to view the content of your Android device in your
DevTools instance.
Clicks are translated into taps, firing proper touch events on the device.
Keystrokes on your computer are sent to the device.
To simulate a pinch gesture, hold Shift while dragging.
To scroll, use your trackpad or mouse wheel, or fling with your mouse pointer
3. Example
4. Levels Applicable To
White Box Testing method is applicable to the following levels of software testing:
Testing can be commenced at an earlier stage. One need not wait for the GUI
to be available.
Testing is more thorough, with the possibility of covering most paths.
6. Disadvantages
Since tests can be very complex, highly skilled resources are required, with a
thorough knowledge of programming and implementation.
Test script maintenance can be a burden if the implementation changes too
frequently.
Since this method of testing is closely tied to the application being tested, tools
to cater to every kind of implementation/platform may not be readily
available.
The testing can be done at system, integration and unit levels of software
development. One of the basic goals of whitebox testing is to verify a working
flow for an application. It involves testing a series of predefined inputs against
expected or desired outputs so that when a specific input does not result in
the expected output, you have encountered a bug.
The first thing a tester will often do is learn and understand the source code of
the application. Since white box testing involves the testing of the inner
workings of an application, the tester must be very knowledgeable in the
programming languages used in the applications they are testing. Also, the
testing person must be highly aware of secure coding practices. Security is
often one of the primary objectives of testing software. The tester should be
able to find security issues and prevent attacks from hackers and naive users
who might inject malicious code into the application either knowingly or
unknowingly.
The second basic step to white box testing involves testing the application's
source code for proper flow and structure. One way is by writing more code to
test the application's source code. The tester will develop little tests for each
process or series of processes in the application. This method requires that
the tester must have intimate knowledge of the code and is often done by the
developer. Other methods include Manual Testing, trial, and error testing and
the use of testing tools as we will explain further on in this article.
The goal of WhiteBox testing is to verify all the decision branches, loops,
statements in the code.
To exercise the statements in the above code, WhiteBox test cases would be
A = 1, B = 1
A = -1, B = -3
White Box Testing Techniques
A major White box testing technique is Code Coverage analysis. Code
Coverage analysis eliminates gaps in a Test Case suite. It identifies areas of a
program that are not exercised by a set of test cases. Once gaps are
identified, you create test cases to verify untested parts of the code, thereby
increasing the quality of the software product
Branch Coverage - This technique checks every possible path (if-else and
other conditional loops) of a software application.
Apart from above, there are numerous coverage types such as Condition
Coverage, Multiple Condition Coverage, Path Coverage, Function Coverage
etc. Each technique has its own merits and attempts to test (cover) all parts of
software code. Using Statement and Branch coverage you generally attain 80-
90% code coverage which is sufficient.
Veracode
EclEmma
RCUNIT
NUnit
JSUnit
JUnit
CppUnit
White box testing can be quite complex. The complexity involved has a
lot to do with the application being tested. A small application that
performs a single simple operation could be white box tested in few
minutes, while larger programming applications take days, weeks and
even longer to fully test.
White box testing should be done on a software application as it is being
developed after it is written and again after each modification.
In BlackBox Testing we just focus on inputs and output of the software system
without bothering about internal knowledge of the software program.
The above Black-Box can be any software system you want to test. For
Example, an operating system like Windows, a website like Google, a database
like Oracle or even your own custom application. Under Black Box Testing, you
can test these applications by just focusing on the inputs and outputs without
knowing their internal code implementation.
Functional testing - This black box testing type is related to the functional
requirements of a system; it is done by software testers.
Non-functional testing - This type of black box testing is not related to testing
of specific functionality, but non-functional requirements such as
performance, scalability, usability.
Regression testing - Regression Testing is done after code fixes, upgrades
or any other system maintenance to check the new code has not affected
the existing code.
the main focus of black box testing is White Box Testing (Unit Testing)
on the validation of your functional validates internal structure and
requirements. working of your software code
Equivalence Class
Domain Tests
Orthogonal Arrays
Decision Tables
State Models
Exploratory Testing
All-pairs testing
#Test Automation of Mobile Apps
It doesn't matter how much time you invest in design and implementation ,
mistakes are inevitable, and bugs will appear.
2. Android Testing Strategy
A correct android testing strategy should include the following
1. Unit Test
2. Integration Test
3. Operational Test
4. System Test
3. Unit tests
Unit Tests include sets of one or more programs which are designed to verify
an atomic unit of source code, such as a method or a class.
Android platform comes pre-integrated Junit 3.0 framework. It's open source
framework for automating Unit Testing. Android Testing Framework is powerful
tool for developer to write the effective unit test program.
The integration of Android and JUnit framework
An addition to Unit Testing is User Interface (UI) tests. These tests relate to UI
components of your target application. UI tests ensure that your application
return the correct UI output in response to sequence of user actions on
device.
There's many testing frameworks are used to conduct integration test for
Android such as Troyd, Robolectric, Robotium.
5. Operational tests
Operational are also called Functional Tests or Acceptation Tests. They
are high level tests designed to check the completeness and
correctness of application.
In Android, FitNesse is open-source framework that makes it easy to
conduct operational tests for target application.
6. System tests
In System Testing the system is tested as a whole and the interaction between
the components, software and hardware is checked.
GUI tests
Usability tests
Performance tests
Stress tests
In the above list, Performance Testing is given more focus. You can use tools
like Traceview to conduct performance test on Android .This tool can help you
debug your application and profile its performance.
2a) Test tools: A SDK tools for building test. They are integrated in
Eclipse IDE or run as command line.
3. Test package are organized into test projects. This package follows
naming convention. If the application under test has a package name of
"com.mydomain.myapp" than Test package should be
"com.mydomain.myapp.test" .Test package includes 2 objects as below:
3b) Mock objects : includes mock data that will be used as sample
input for test cases.
9. Android Test Case Classes
Operation of Robolectric
Myth #1:All Android devices are the same... test on emulators is enough
Emulators are not sufficient for your mobile testing. You must test your app
on real devices.
Generally in all testing, we design the test cases then execute them. But
in Exploratory testing, test design and execution all will be done
together.
In exploratory testing, there's no plan and no preparation, then tester
would do tests that he wants to do. Some functions will be tested
repeatedly, while some functions will not be tested altogether.
If application doesn't work and has bugs, users uninstall your app
Quality issues are the first reason for bad review in Google Play. It
affects to your reputation and you lose customer's trust.
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.
JUnit
Monkey
JUnit
You can use the JUnit TestCase class to do unit testing on a class that
doesn't call Android APIs. TestCase is also the base class for AndroidTestCase,
which you can use to test Android-dependent objects. Besides providing the
JUnit framework, AndroidTestCase offers Android-specific setup, teardown,
and helper methods.
In order to use TestCase, extend your class with TestCase class and
implement a method call setUp(). Its syntax is given below −
fValue1= 2.0;
fValue2= 3.0;
For each test implement a method which interacts with the fixture. Verify the
expected results with assertions specified by calling assertTrue(String,
boolean) with a boolean.
assertTrue(result == 5.0);
The assert methods compare values you expect from a test to the actual
results and throw an exception if the comparison fails.
Once the methods are defined you can run them. Its syntax is given below −
test.run();
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.
You use it to stress-test your application and report back errors that are
encountered. You can repeat a stream of events by running the tool each
time with the same random number seed.
Monkey features
Monkey has many features, but it can be all be summed up to these four
categories.
Operational constraints
Debugging options
Monkey Usage
In order to use monkey, open up a command prompt and just navigate to
the following directory.
android ->sdk ->platform-tools
Once inside the directory, attach your device with the PC , and run the
following command.
adb shell monkey -p your.package.name -v 500
adb - Android Debug Bridge. A tool used to connect and sends commands to
your Android phone from a desktop or laptop computer.
shell - shell is just an interface on the device that translates our commands to
system commands.
500- it is the frequency conut or the number of events to be sent for testing.
This has also been shown in the figure below. By typing this command , you
are actually generating 500 random events for testing.
Example
The below example demonstrates the use of Testing. It crates a basic
application which can be used for monkey.
To experiment with this example, you need to run this on an actual device
and then follow the monkey steps explained in the beginning.
Steps Description
6 Run the application and choose a running android device and install the
application on it and verify the results.
package com.tutorialspoint.myapplication;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
Button b1;
@Override
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
b1=(Button)findViewById(R.id.button);
}
public void button(View v){
startActivity(in);
package com.tutorialspoint.myapplication;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
@Override
super.onCreate(savedInstanceState);
setContentView(R.layout.view);
Button b1=(Button)findViewById(R.id.button2);
b1.setOnClickListener(new View.OnClickListener() {
@Override
});
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
tools:context=".MainActivity">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/textView"
android:textSize="25sp"
android:layout_centerHorizontal="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Tutorials point"
android:id="@+id/textView2"
android:layout_below="@+id/textView"
android:layout_alignRight="@+id/textView"
android:layout_alignEnd="@+id/textView"
android:textColor="#ff36ff15"
android:textIsSelectable="false"
android:textSize="35dp" />
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/imageView"
android:src="@drawable/abc"
android:layout_below="@+id/textView2"
android:layout_centerHorizontal="true" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button"
android:onClick="button"
android:id="@+id/button"
android:layout_below="@+id/imageView"
android:layout_centerHorizontal="true"
android:layout_marginTop="100dp" />
</RelativeLayout>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent" android:layout_height="match_parent">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="button"
android:id="@+id/button2"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/textView3"
android:textColor="#ff3aff22"
android:textSize="35dp"
android:layout_above="@+id/button2"
android:layout_centerHorizontal="true"
android:layout_marginBottom="90dp" />
</RelativeLayout>
</resources>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.tutorialspoint.myapplication" >
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="@string/app_name" >
<intent-filter>
</intent-filter>
</activity>
<activity android:name=".second"></activity>
</application>
</manifest>
Let's try to run your Android Testing application. I assume you have
connected your actual Android Mobile device with your computer. To run the
app from Android studio, open one of your project's activity files and click
Run icon from the toolbar. Before starting your application, Android studio
will display following window to select an option where you want to run your
Android application.
Select your mobile device as an option and then check your mobile device
which will display application screen. Now just follow the steps mentioned at
the top under the monkey section in order to perform testing on this
application.
# Junit For Android Apps
Automated unit testing saves time by performing many tests for you. It can also be used as a quick way to
validate new builds-in the form of build acceptance or smoke tests. Finally, unit testing can be an effective
way to verify each area of functionality within your application performs as expected across a wide range
of devices in a systematic and reproducible fashion. The Android SDK supports JUnit for automated unit
tests.
For an existing Android project, right-click on the project in Eclipse, choose "Android Tools", then "New
Testing Project, as highlighted below:
For a new Android project in Eclipse, on the "New Android Project" dialog, press the "Next" button,
highlighted below:
Regardless of which method you follow, you'll be able to create a new test project for your Android project
at this time. The test project creation dialog, shown below, will usually fill in the appropriate details with
some standard naming conventions. If not, fill them in yourself and create the project.
2. Creating a JUnit Test Case in Android
Android applications are normally comprised of a number of Activity classes. In fact, an activity is a largely
independent entity and can be tested and exercised as a cohesive unit. The Android SDK includes
several classes to test your Activity classes. We'll use one now.
Click the Finish button and this new class will be created for you. The default constructor that the wizard
creates isn't right just yet. Change it so that it takes no parameters, but calls a different super()method,
like so:
public ScreenValidation() {
super("com.mamlambo.testingproject.TestingProjectActivity",
TestingProjectActivity.class);
}
The setUp() method should be used to configure anything needed to run all of the associated tests in
this test case. The Activity instance is available at any time by calling the getActivity() method. So,
for instance, if we wanted to acquire a handle to a TextView that appears within this Activity class to use
in all of our tests, we could implement the setUp() method as follows:
TextView helloText;
protected void setUp() throws Exception {
super.setUp();
helloText = (TextView) getActivity().
findViewById(R.id.hello_textview);
}
// ... and so on
}
All test methods must start with "test" followed by a descriptive test name. In this case, we've created a
test named "Hello Text Visibility." The assertFalse() calls are what determine if the test ultimately
passes or fails. (The assertTrue() method can be used as well, for values that must be true to pass.)
To run tests and tests cases you've created, click on the Debug drop down from within Eclipse, choose
Debug As, then Android JUnit Test. You can also create an Android JUnit Test configuration to customize
these settings, if you prefer.
Our little app passes the "Hello Text Visibility" test with flying colors… when our device is in landscape
mode:
...But when in portrait mode, our Activity fails the test:
Apparently our layout isn't designed to display correctly in portrait mode. (Hint: Perhaps this has
something to do with setting the width to more pixels than the phone has rather than using a more
appropriate unit like dp or just match_parent.)
You should run your tests on all target devices and configurations you expect to support. Our simple unit
test example has more overhead per test than you'd normally find. If your test takes a long time to run,
you may want to set up several to run in parallel.
It's also not particularly useful to your app to test Android (or Java) framework functionality. For example,
performing a test where you set the text value on a field and then read it back to see if it's the same. If the
test is being performed on a regular TextView, the test won't be particularly meaningful (unless you're
implementing the SDK on a new device). However, if you've creating your own implementation of
TextView, by all means--test it. In other words, testing tautologies isn't a very good use of time and
resources.
That's not to say that any code base is bug free, but testing things that are equivalent to testing if one
equals one isn't worth the effort to write the test to begin with. If that fails, you've got bigger problems than
your app. There's also a subtle difference between testing the SDK and testing that we're using the SDK
correctly (in the above example, we weren't).
Therefore, if you're new to automated unit testing in general, we recommend you do some research into
the subject. A good place to start is JUnit.org.