0% found this document useful (0 votes)
110 views63 pages

Debug Your App: Unit-Iv

Debug your app by setting breakpoints, examining variables, and evaluating expressions at runtime. Enable debugging on your device or emulator, then start a debugging session by selecting a device and clicking Debug. You can also attach the debugger to a running app. Use the Logcat window to view system logs and debug messages written from your code.

Uploaded by

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

Debug Your App: Unit-Iv

Debug your app by setting breakpoints, examining variables, and evaluating expressions at runtime. Enable debugging on your device or emulator, then start a debugging session by selecting a device and clicking Debug. You can also attach the debugger to a running app. Use the Logcat window to view system logs and debug messages written from your code.

Uploaded by

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

UNIT-IV

Debug your app


Android Studio provides a debugger that allows you to do the following and more:

 Select a device to debug your app on.


 Set breakpoints in your Java, Kotlin, and C/C++ code.
 Examine variables and evaluate expressions at runtime.

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:

1. Set some breakpoints in the app code.

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

Attach the debugger to a running app


If your app is already running on your device, you can start debugging without restarting
your app as follows:

1. Click Attach debugger to Android process .


2. In the Choose Process dialog, select the process you want to attach the debugger to.
If you're using an emulator or a rooted device, you can check Show all processes to
see all processes.
From the Debugger drop-down menu, you can select a different debug type. By default,
Android Studio uses the Auto debug type to select the best debugger option for you,
based on whether your project includes Java or C/C++ code.
3. Click OK.
The Debug window appears.
Note: The Android Studio debugger and garbage collector are loosely integrated. The Android
virtual machine guarantees that any object the debugger is aware of is not garbage collected until
after the debugger disconnects. This can result in a buildup of objects over time while the debugger
is connected. For example, if the debugger sees a running thread, the associated Thread object is
not garbage collected until the debugger disconnects, even if the thread has terminated.

3. Change the debugger type


Because different debugger tools are required to debug Java/Kotlin code and C/C++
code, the Android Studio debugger allows you to select which debugger type to use. By
default, Android Studio decides which debugger to use based on which languages it
detects in your project (with the Auto debugger type). However, you can manually
select the debugger in the debug configuration (click Run > Edit Configurations) or in
the dialog that appears when you click Run > Attach debugger to Android process.

The debug types available include the following:

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

4. Use the system log


The system log shows system messages while you debug your app. These messages
include information from apps running on the device. If you want to use the system log
to debug your app, make sure your code writes log messages and prints the stack trace
for exceptions while your app is in the development phase.

Write log messages in your code


To write log messages in your code, use the Log class. Log messages help you
understand the execution flow by collecting the system debug output while you interact
with your app. Log messages can tell you what part of your application failed. For more
information about logging, see Write and view logs.

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.

View the system log


You can view and filter debug and other system messages in the Logcat window. For
example, you can see messages when garbage collection occurs, or messages that you
add to your app with the Log class.

To use logcat, start debugging and select the Logcat tab in the bottom toolbar as
shown in figure 3.

Figure 3. Logcat window with filter settings

For a description of logcat and its filtering options, see Write and view logs with Logcat.

5. Work with breakpoints


Android Studio supports several types of breakpoints that trigger different debugging
actions. The most common type is a line breakpoint that pauses the execution of your
app at a specified line of code. While paused, you can examine variables, evaluate
expressions, then continue execution line by line to determine the causes of runtime
errors.

To add a line breakpoint, proceed as follows:

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

click Attach debugger to Android proccess . Otherwise, start debugging by

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.

Figure 4. Debugging native code using LLDB

1. Android Studio switches to the <your-module> tab when LLDB debugger


encounters a breakpoint in your C/C++ code. The Frames, Variables,
and Watches panes are also available and work exactly as they would if you were
debugging Java code. Although the Threads pane is not available in the LLDB
session view, you can access your app processes using the drop-down list in
the Frames pane. You can learn more about these panes in the sections about how
to debug window frames and inspect variables.
Note: While inspecting a breakpoint in your native code, the Android system suspends the
virtual machine that runs your app’s Java bytecode. This means that you are unable to interact
with the Java debugger or retrieve any state information from your Java debugger session while
inspecting a breakpoint in your native code.
2. Android Studio switches to the <your-module>-java tab when the Java debugger
encounters a breakpoint in your Java code.
3. While debugging with LLDB, you can use the LLDB terminal in the LLDB session
view to pass command line options to LLDB. If you have certain commands that
you would like LLDB to execute each time you start debugging your app, either just
before or just after the debugger attaches to your app process, you can add those
commands to your debug configuration.

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.

View and configure breakpoints


To view all the breakpoints and configure breakpoint settings, click View
Breakpoints on the left side of the Debug window. The Breakpoints window
appears, as shown in figure 5.

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.

Debug window frames


In the Debugger window, the Frames pane lets you inspect the stack frame that
caused the current breakpoint to be hit. This enables you to navigate and examine the
stack frame and also inspect the list of threads in your Android app. To select a thread,
use the thread selector drop-down and view its stack frame. Clicking the elements in the
frame opens the source in the editor. You can also customize the thread presentation
and export the stack frame as discussed in the Window Frames guide.
6. Inspect variables
In the Debugger window, the Variables pane lets you inspect variables when the
system stops your app on a breakpoint and you select a frame from the Frames pane.
The Variables pane also lets you evaluate ad-hoc expressions using static methods
and/or variables available within the selected frame.

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.

To add a variable or expression to the Watches list, follow these steps:

1. Begin debugging.

2. In the Watches pane, click Add .


3. In the text box that appears, type the name of the variable or expression you want to
watch and then press Enter.

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 .

Figure 6. The Variables and Watches panes in the Debugger window


Add watchpoints
While debugging C/C++ code, you can set special types of breakpoints,
called watchpoints, that can suspend your app process when your app interacts with a
particular block of memory. For example, if you set two pointers to a block of memory
and assign a watchpoint to it, using either pointer to access that block of memory
triggers the watchpoint.

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.

To set a watchpoint, you must meet the following requirements:

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

You can create a custom format (data type renderer), as follows:

1. Right-click the resource value.


2. Select View as.
3. Select Create. The Java Data Type Renderers dialog displays.
4. Follow the instructions at Java Data type renderers
#DEBUGGING
Remote debug live content on an Android device from your Windows, Mac, or Linux
computer. This tutorial teaches you how to:

 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

6. In DevTools, open the Settings tab.


7. Make sure that the Discover USB devices checkbox is enabled.
Figure 3. The Discover USB Devices checkbox is enabled

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

9. If your device is showing up as Unknown, accept the Allow USB


Debugging permission prompt on your Android device.

Troubleshooting: DevTools is not detecting the Android device


Make sure that your hardware is set up correctly:

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

Make sure that your software is set up correctly:


 If your development machine is running Windows, try manually installing the USB drivers for
your Android device. See Install OEM USB Drivers.
 Some combinations of Windows and Android devices (especially Samsung) require extra set
up. See Chrome DevTools Devices does not detect device when plugged in.

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!

2. Step 2: Debug content on your Android device from your


development machine
1. Open Chrome on your Android device.
2. In the Remote Devices tab, click the tab that matches your Android device model
name. At the top of this page, you see your Android device's model name, followed by
its serial number. Below that, you can see the version of Chrome that's running on the
device, with the version number in parentheses. Each open Chrome tab gets its own
section. You can interact with that tab from this section. If there are any apps using
WebView, you see a section for each of those apps, too. In Figure 5 there are no tabs
or WebViews open.
Figure 5. A connected remote device

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.

More actions: reload, focus, or close a tab


Click More Options next to the tab that you want to reload, focus, or close.

Figure 6. The menu for reloading, focusing, or closing a tab

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.

Screencast your Android screen to your development machine

Click Toggle Screencast to view the content of your Android device in your
DevTools instance.

You can interact with the screencast in multiple ways:

 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

#White Box Testing


WHITE BOX TESTING (also known as Clear Box Testing, Open Box Testing,
Glass Box Testing, Transparent Box Testing, Code-Based Testing or Structural
Testing) is a software testing method in which the internal
structure/design/implementation of the item being tested is known to the tester. The
tester chooses inputs to exercise paths through the code and determines the
appropriate outputs. Programming know-how and the implementation knowledge is
essential. White box testing is testing beyond the user interface and into the nitty-
gritty of a system.
This method is named so because the software program, in the eyes of the tester, is
like a white/transparent box; inside which one clearly sees.
Definition by ISTQB

 white-box testing: Testing based on an analysis of the internal structure of


the component or system.
 white-box test design technique: Procedure to derive and/or select test cases
based on an analysis of the internal structure of a component or system.

3. Example

A tester, usually a developer as well, studies the implementation code of a certain


field on a webpage, determines all legal (valid and invalid) AND illegal inputs and
verifies the outputs against the expected outcomes, which is also determined by
studying the implementation code.
White Box Testing is like the work of a mechanic who examines the engine to see
why the car is not moving.

4. Levels Applicable To

White Box Testing method is applicable to the following levels of software testing:

 Unit Testing: For testing paths within a unit.


 Integration Testing: For testing paths between units.
 System Testing: For testing paths between subsystems.

However, it is mainly applied to Unit Testing.


5. Advantages

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

7. What do you verify in White Box Testing?


White box testing involves the testing of the software code for the following:

 Internal security holes


 Broken or poorly structured paths in the coding processes
 The flow of specific inputs through the code
 Expected output
 The functionality of conditional loops
 Testing of each statement, object, and function on an individual basis

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.

How do you perform White Box Testing?


To give you a simplified explanation of white box testing, we have divided it
into two basic steps. This is what testers do when testing an application using
the white box testing technique:
STEP 1) UNDERSTAND THE SOURCE CODE

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.

Step 2) CREATE TEST CASES AND EXECUTE

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.

WhiteBox Testing Example


Consider the following piece of code

Printme (int a, int b) { ------------ Printme is a function


int result = a+ b;
If (result> 0)
Print ("Positive", result)
Else
Print ("Negative", result)
} ----------- End of the source code

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

There are automated tools available to perform Code coverage


analysis. Below are a few coverage analysis techniques

Statement Coverage:- This technique requires every possible statement in


the code to be tested at least once during the testing process of software
engineering.

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.

Types of White Box Testing


White box testing encompasses several testing types used to evaluate the
usability of an application, block of code or specific software package. There
are listed below --

 Unit Testing: It is often the first type of testing done on an


application. Unit Testing is performed on each unit or block of code as it
is developed. Unit Testing is essentially done by the programmer. As a
software developer, you develop a few lines of code, a single function or
an object and test it to make sure it works before continuing Unit Testing
helps identify a majority of bugs, early in the software development
lifecycle. Bugs identified in this stage are cheaper and easy to fix.
 Testing for Memory Leaks: Memory leaks are leading causes of
slower running applications. A QA specialist who is experienced at
detecting memory leaks is essential in cases where you have a slow
running software application.
Apart from above, a few testing types are part of both black box and white box
testing. They are listed as below

 White Box Penetration Testing: In this testing, the tester/developer


has full information of the application's source code, detailed network
information, IP addresses involved and all server information the
application runs on. The aim is to attack the code from several angles
to expose security threats
 White Box Mutation Testing: Mutation testing is often used to discover
the best coding techniques to use for expanding a software solution.

White Box Testing Tools


Below is a list of top white box testing tools.

 Veracode
 EclEmma
 RCUNIT
 NUnit
 JSUnit
 JUnit
 CppUnit

Advantages of White Box Testing


 Code optimization by finding hidden errors.
 White box tests cases can be easily automated.
 Testing is more thorough as all code paths are usually covered.
 Testing can start early in SDLC even if GUI is not available.

Disadvantages of WhiteBox Testing


 White box testing can be quite complex and expensive.
 Developers who usually execute white box test cases detest it. The
white box testing by developers is not detailed can lead to production
errors.
 White box testing requires professional resources, with a detailed
understanding of programming and implementation.
 White-box testing is time-consuming, bigger programming applications
take the time to test fully.
Ending Notes:

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

#BLACK BOX TESTING


What is Black Box Testing?
Black box testing is defined as a testing technique in which functionality of the
Application Under Test (AUT) is tested without looking at the internal code
structure, implementation details and knowledge of internal paths of the
software. This type of testing is based entirely on software requirements and
specifications.

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.

How to do BlackBox Testing


Here are the generic steps followed to carry out any type of Black Box Testing.
 Initially, the requirements and specifications of the system are examined.
 Tester chooses valid inputs (positive test scenario) to check whether SUT
processes them correctly. Also, some invalid inputs (negative test
scenario) are chosen to verify that the SUT is able to detect them.
 Tester determines expected outputs for all those inputs.
 Software tester constructs test cases with the selected inputs.
 The test cases are executed.
 Software tester compares the actual outputs with the expected outputs.
 Defects if any are fixed and re-tested.

Types of Black Box Testing


There are many types of Black Box Testing but the following are the prominent
ones -

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

Tools used for Black Box Testing:


Tools used for Black box testing largely depends on the type of black box testing
you are doing.

 For Functional/ Regression Tests you can use - QTP, Selenium


 For Non-Functional Tests, you can use - LoadRunner, Jmeter

Black Box Testing Techniques


Following are the prominent Test Strategy amongst the many used in Black box
Testing

 Equivalence Class Testing: It is used to minimize the number of


possible test cases to an optimum level while maintains reasonable test
coverage.
 Boundary Value Testing: Boundary value testing is focused on the
values at boundaries. This technique determines whether a certain range
of values are acceptable by the system or not. It is very useful in reducing
the number of test cases. It is most suitable for the systems where an
input is within certain ranges.
 Decision Table Testing: A decision table puts causes and their effects
in a matrix. There is a unique combination in each column.

Comparison of Black Box and White Box


Testing:

Black Box Testing White Box Testing

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

Black box testing gives abstraction To conduct White Box Testing,


from code and focuses on testing knowledge of underlying programming
effort on the software system language is essential. Current day
behavior. software systems use a variety of
programming languages and
technologies and its not possible to
know all of them.
Black box testing facilitates testing White box testing does not facilitate
communication amongst modules testing communication amongst
modules

Black Box Testing and Software Development


Life Cycle (SDLC)
Black box testing has its own life cycle called Software Testing Life Cycle
(STLC) and it is relative to every stage of Software Development Life Cycle of
Software Engineering.

 Requirement - This is the initial stage of SDLC and in this stage, a


requirement is gathered. Software testers also take part in this stage.
 Test Planning & Analysis - Testing Types applicable to the project are
determined. A Test Plan is created which determines possible project
risks and their mitigation.
 Design - In this stage Test cases/scripts are created on the basis of
software requirement documents
 Test Execution- In this stage Test Cases prepared are executed. Bugs
if any are fixed and re-tested.

Behavioural Testing Techniques:


There are different techniques involved in Black Box testing.

 Equivalence Class

 Boundary Value Analysis

 Domain Tests

 Orthogonal Arrays

 Decision Tables

 State Models

 Exploratory Testing

 All-pairs testing
#Test Automation of Mobile Apps

1. Why Android Testing?


Android is the largest operating system in the world. At the same time,
Android is fragmented. there are tons of devices and Android versions that
your app must be compatible with.

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.

Common user UI actions on application

The common way to performance UI tests on device is Android Instrumentation.


But this has performance issues. One of the best tools to conduct UI testing
on Android is Robotium .
4. Integration tests
In Integration Testing, all unit tested modules, are combined and verified. In
Android, integration tests often involve checking integration withAndroid
components such as Service testing, Activity testing, Content Provider testing,
etc

Types of integration test on Android

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.

In Android, System Testing normally includes

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

7. Automated ANDROID TESTING


As android is fragmented, testing on multitude of devices is necessary. But
this will also cost you money. Automated Android Testing can help reduce
costs

Benefits of automated android testing

 Reduce time for executing test cases


 Increase productivity of your development process
 Early bug detection, save cost on software maintenance
 Quickly found and fix the bugs on implementation
 Ensure the quality of software

We will study the following 2 frameworks

 Android Testing framework


 Robolectric Testing framework

8. Android testing framework


One of the standard testing frameworks for Android application is Android
testing framework. It is a powerful and easy-to-use testing framework that is
well integrated with the Android SDK tools.
Android testing framework Architecture

1. Application package is your target application which needs to be


tested
2. InstrumentationTestRunner is the Test Case runner that executes test
case on target application. It includes:

2a) Test tools: A SDK tools for building test. They are integrated in
Eclipse IDE or run as command line.

2b) MonkeyRunner: A tool that provides APIs for writing program


which control an Android device or emulator outside of Android code.

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:

3a) Test case classes:include test methods to executed on target


application.

3b) Mock objects : includes mock data that will be used as sample
input for test cases.
9. Android Test Case Classes

AndroidTestCase class diagram

1. TestCase includes JUnit methods to run JUnit test


2. TestSuite is used to run set of test cases
3. InstrumentationTestSuite is a TestSuite that injects Instrumentation
into InstrumentationTestCase before running them.
4. InstrumentationTestRunner is the test case runner that execute test
case on target application.
5. AndroidTestCase extends JUnit TestCase. It contains methods for
accessing resources like Activity Context.
6. ApplicationTestCase verifies the Application classes in a controlled
environment.
7. InstrumentationTestCase verifies a particular feature or behavior of
target application , for e.g., verify UI output of application.
8. ActivityTestCase is base class that supports testing the Application
Activities.
9. ProviderTestCase is class for testing single ContentProvider.
10. ServiceTestCase is used to test Service classes in testing
environment. It also supports Service's life cycle.
11. SingeLauchActivityTestCase is used to test single Activity with
an InstrumentationTestCase.
12. ActivityUnitTestCase <Activity> is used to test single isolated
activity.
13. ActivityInstrumentationTestCase2<Activity> extends the JUnit
TestCase class. It connects you to target application with
instrumentation. With this class, you can access application's GUI
component and send UI event (keystroke or touch event) to the UI.

Below is an example of ActivityInstrumentationTestCase. It verifies the UI


operation of Calculator application, check the correctness of the UI outputs.
ActivityInstrumentationTestCase2 testing example

10. Robolectric testing framework


Testing using Android Testing framework with device or emulator is difficult.
Building and running test is slow and take much development effort. To fix this
problem, there's another choice - Robolectric testing framework.
Robolectric framework allows you to run Android tests directly on
JVM without the need for a device or an emulator.

Advance features of Robolectric


11. Robolectric Test Case Classes

Operation of Robolectric

 As shown above, Robolectric can perform following actions:


 Register and create a Shadow class
 Intercept the loading of Android class
 Uses javaassist to override the method bodies of Android class
 Bind Shadow object to Android class
 This allows the code under test to execute without Android environment.

12. Others testing framework


Besides testing frameworks which were mentioned above, there are many
other testing frameworks such as:
 Android Junit Report, a custom instrumentation test runner for Android
that generates XML reports for integration with other tools.
 Expresso
 Appium

13. Myths of Android Testing


Many enterprises develop android Testing strategies that are based on
common misconceptions. This section examines a few popular myths and
realities of Android testing.

Myth #1:All Android devices are the same... test on emulators is enough

Let's start with a simple example. An application works perfectly on emulator s


but on some real devices, it crashes during execution

Application crashes during execution on real device

Emulators are not sufficient for your mobile testing. You must test your app
on real devices.

Myth #2:Testing on some common devices is enough

 On different devices, your application looks different because different


devices have different hardware, screen sizes, memory etc. You must
test your application on different devices, OS versions, carrier networks
and locations.
Myth#3:Exploratory testing just before launch is enough

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

Myth#4:If there some bugs in application, users will understand

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

Therefore its essential to have a proper android testing strategy in place

14. Best practices in Android Testing


 Application developers should create the test cases at the same time
when they are writing the code
 All test cases should be stored in version control-together with source
code
 Use continuous integration and run tests every time the code is
changed
 Avoid using emulators and rooted devices
# Junit For Android Apps
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.

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.

Testing Tools in android


There are many tools that can be used for testing android applications. Some
are official like Junit,Monkey and some are third party tools that can be used
to test android applications. In this chapter we are going to explain these two
tools to test android applications.

 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 −

public class MathTest extends TestCase {

protected double fValue1;


protected double fValue2;

protected void setUp() {

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.

public void testAdd() {

double result= fValue1 + fValue2;

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 −

TestCase test= new MathTest("testAdd");

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.

 Basic configuration options

 Operational constraints

 Event types and frequencies

 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

This command can be broken down into these steps.

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

 monkey - monkey is the testing tool.

 v - v stands for verbose method.

 500- it is the frequency conut or the number of events to be sent for testing.

This is also shown in the figure −


In the above command, you run the monkey tool on the default android UI
application. Now in order to run it to your application , here what you have
to do.

finally you will get finish as shown bellow

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

1 You will useAndroid studio to create an Android application under a


package com.tutorialspoint.myapplication.

2 Modify src/MainActivity.java file to add Activity code.


3 Modify layouta XML file res/layout/activity_main.xml add any GUI
component if required.

4 Create src/second.java file to add Activity code.

5 Modify layout XML file res/layout/view.xml add any GUI component if


required.

6 Run the application and choose a running android device and install the
application on it and verify the results.

Here is the content of MainActivity.java.

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;

public class MainActivity extends AppCompatActivity {

Button b1;

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

b1=(Button)findViewById(R.id.button);

}
public void button(View v){

Intent in =new Intent(MainActivity.this,second.class);

startActivity(in);

Here is the content of second.java.

package com.tutorialspoint.myapplication;

import android.app.Activity;

import android.os.Bundle;

import android.view.View;

import android.widget.Button;

import android.widget.Toast;

public class second extends Activity{

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.view);

Button b1=(Button)findViewById(R.id.button2);

b1.setOnClickListener(new View.OnClickListener() {

@Override

public void onClick(View v) {


Toast.makeText(second.this,"Thanks",Toast.LENGTH_SHORT).show();

});

Here is the content of activity_main.xml.


In the below code abc indicates the logo of tutorialspoint.com

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

<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:text="UI Animator Viewer"

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>

Here is the content of view.xml

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

<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:text="Tutorials point "

android:id="@+id/textView3"

android:textColor="#ff3aff22"

android:textSize="35dp"

android:layout_above="@+id/button2"

android:layout_centerHorizontal="true"

android:layout_marginBottom="90dp" />

</RelativeLayout>

Here is the content of Strings.xml.


<resources>

<string name="app_name">My Application</string>

</resources>

Here is the content of AndroidManifest.xml.

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

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

<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />

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

1. Creating a JUnit Project for Android


If you already have an Eclipse project for your Android application, that's a good place to start. If you don't
already have an Eclipse project, you can create the JUnit project at the same time as you create your
Android project.

For an existing Android project, right-click on the project in Eclipse, choose "Android Tools", then "New
Testing Project, as highlighted below:

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.

Right-click on your test project. Choose New, JUnit Test Case:


Now fill out the New JUnit Test Case dialog with appropriate values. The superclass to use
is android.test.ActivityInstrumentTestCase2, where T is the Activity we're going to test.

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);
}

1. Adding a Unit Test to Android


You can craft tests for all sorts of reasons. You have access to all the screen controls on the Activity's
layout as well as any code in your app. Since we're using an activity test case, we're probably interested
in something to do with the user interface, the Activity's layout, or its functionality. Let's find out if the
TextView control fits on the screen.

public void testHelloTextVisibility() {


View container = getActivity().findViewById(R.id.container_layout);
int boundaryWidth = container.getWidth();
int boundaryHeight = container.getHeight();

int[] location = new int[2];


container.getLocationOnScreen(location);

int[] helloTextLocation = new int[2];


helloText.getLocationOnScreen(helloTextLocation);

Rect textRect = new Rect();


helloText.getDrawingRect(textRect);

boolean widerThanBoundary = (textRect.width() > boundaryWidth);


boolean tallerThanBoundary = (textRect.height() > boundaryHeight);
boolean extendsOffRight = location[0] + boundaryWidth
> helloTextLocation[0] + textRect.width();
assertTrue("Text wider than boundary", widerThanBoundary);
assertTrue("Text taller than boundary", tallerThanBoundary);
assertTrue("Text goes off right side", extendsOffRight);

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

2. Android App Quality Only As Good As the Unit Tests


Care must be taken when creating unit tests. If a test passes but isn't testing for the correct values and
behaviors, that won't produce any sort of useful results. In fact, it can be dangerous as it might mask
problems. The development of test cases is just as important as the development of the code itself. The
primary way to test the test cases is by doing careful code reviews and make sure they're testing what
you think they are.

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.

You might also like