Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Newsletter Hub
Free Learning
Arrow right icon
timer SALE ENDS IN
0 Days
:
00 Hours
:
00 Minutes
:
00 Seconds
Learning Android Application Testing
Learning Android Application Testing

Learning Android Application Testing

Improve your Android applications through intensive testing and debugging

$43.99
By Paul Blundell
Full star icon Full star icon Full star icon Half star icon Empty star icon
3.8 (4 Ratings)
Pages 274
Published in Mar 2015
Product Type eBook
Edition 1st Edition
ISBN 9781784397999
Learning Android Application Testing

Packt Subscriptions

See our plans and pricing
Modal Close icon
$12.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 6,500+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
$129.99 billed annually
Feature tick icon Unlimited access to Packt's library of 6,500+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just $5 each
Feature tick icon Exclusive print discounts
$179.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 6,500+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just $5 each
Feature tick icon Exclusive print discounts

What do you get with eBook?

Product feature icon Instant access to your Digital eBook purchase
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
Table of content icon View table of contents Preview book icon Preview Book

Learning Android Application Testing

Chapter 2. Understanding Testing with the Android SDK

We now know how to create tests inside an Android project and how to run these tests. It is now time to start digging a bit deeper to recognize the building blocks available to create more useful tests.

In this second chapter, we will be covering the following topics:

  • Common assertions

  • View assertions

  • Other assertion types

  • Helpers to test User Interfaces

  • Mock objects

  • Instrumentation

  • TestCase class hierarchies

  • Using external libraries

We will be analyzing these components and showing examples of their use when applicable. The examples in this chapter are intentionally split from the original Android project that contains them. This is done to let you concentrate and focus only on the subject being presented, though the complete examples in a single project can be downloaded as explained later. Right now, we are interested in the trees and not the forest.

Along with the examples presented, we will be identifying reusable common patterns that will...

The demonstration application


A very simple application has been created to demonstrate the use of some of the tests in this chapter. The source for the application can be downloaded from the Packt website at http://packtpub.com

The following screenshot shows this application running:

When reading the explanation of the tests in this chapter, at any point, you can refer to the demo application that is provided in order to see the test in action. The previous simple application has a clickable link, text input, click on a button and a defined layout UI, we can test these one by one.

Assertions in depth


Assertions are methods that check for a condition that can be evaluated. If the condition is not met, the assertion method will throw an exception, thereby aborting the execution of the test.

The JUnit API includes the class Assert. This is the base class of all the TestCase classes that hold several assertion methods useful for writing tests. These inherited methods test for a variety of conditions and are overloaded to support different parameter types. They can be grouped together in the following different sets, depending on the condition checked, for example:

  • assertEquals

  • assertTrue

  • assertFalse

  • assertNull

  • assertNotNull

  • assertSame

  • assertNotSame

  • fail

The condition tested is pretty obvious and is easily identifiable by the method name. Perhaps the ones that deserve some attention are assertEquals() and assertSame(). The former, when used on objects, asserts that both objects passed as parameters are equally calling the objects' equals() method. The latter asserts that both objects...

View assertions


The assertions introduced earlier handle a variety of types as parameters, but they are only intended to test simple conditions or simple objects.

For example, we have asertEquals(short expected, short actual) to test short values, assertEquals(int expected, int actual) to test integer values, assertEquals(Object expected, Object expected) to test any Object instance, and so on.

Usually, while testing user interfaces in Android, you will face the problem of more sophisticated methods, which are mainly related with Views. In this respect, Android provides a class with plenty of assertions in android.test.ViewAsserts (see http://developer.android.com/reference/android/test/ViewAsserts.html for more details), which test relationships between Views and their absolute and relative positions on the screen.

These methods are also overloaded to provide different conditions. Among the assertions, we can find the following:

  • assertBaselineAligned: This asserts that two Views are aligned...

Even more assertions


If the assertions that are reviewed previously do not seem to be enough for your tests' needs, there is still another class included in the Android framework that covers other cases. This class is MoreAsserts (http://developer.android.com/reference/android/test/MoreAsserts.html).

These methods are also overloaded to support different parameter types. Among the assertions, we can find the following:

  • assertAssignableFrom: This asserts that an object is assignable to a class.

  • assertContainsRegex: This asserts that an expected Regex matches any substring of the specified String. It fails with the specified message if it does not.

  • assertContainsInAnyOrder: This asserts that the specified Iterable contains precisely the elements expected, but in any order.

  • assertContainsInOrder: This asserts that the specified Iterable contains precisely the elements expected, but in the same order.

  • assertEmpty: This asserts that an Iterable is empty.

  • assertEquals: This is for some Collections...

The TouchUtils class


Sometimes, when testing UIs, it is helpful to simulate different kinds of touch events. These touch events can be generated in many different ways, but probably android.test.TouchUtils is the simplest to use. This class provides reusable methods to generate touch events in test cases that are derived from InstrumentationTestCase.

The featured methods allow a simulated interaction with the UI under test. The TouchUtils class provides the infrastructure to inject the events using the correct UI or main thread, so no special handling is needed, and you don't need to annotate the test using @UIThreadTest.

TouchUtils supports the following:

  • Clicking on a View and releasing it

  • Tapping on a View (touching it and quickly releasing)

  • Long-clicking on a View

  • Dragging the screen

  • Dragging Views

The following test represents a typical usage of TouchUtils:

    public void testListScrolling() {
        listView.scrollTo(0, 0);

        TouchUtils.dragQuarterScreenUp(this, activity); 
      ...

Mock objects


We have seen the mock objects provided by the Android testing framework in Chapter 1, Getting Started with Testing, and evaluated the concerns about not using real objects to isolate our tests from the surrounding environment.

The next chapter deals with Test-driven Development, and if we were Test-driven Development purists, we can argue about the use of mock objects and be more inclined to use real ones. Martin Fowler calls these two styles the classical and mockist Test-driven Development dichotomy in his great article Mocks aren't stubs, which can be read online at http://www.martinfowler.com/articles/mocksArentStubs.html.

Independent of this discussion, we are introducing mock objects as one of the available building blocks because, sometimes, using mock objects in our tests is recommended, desirable, useful, or even unavoidable.

The Android SDK provides the following classes in the subpackage android.test.mock to help us:

  • MockApplication: This is a mock implementation of...

The TestCase base class


This is the base class of all other test cases in the JUnit framework. It implements the basic methods that we were analyzing in the previous examples (setUp()). The TestCase class also implements the junit.framework.Test interface, meaning it can be run as a JUnit test.

Your Android test cases should always extend TestCase or one of its descendants.

The default constructor

All test cases require a default constructor because, sometimes, depending on the test runner used, this is the only constructor that is invoked, and is also used for serialization.

According to the documentation, this method is not intended to be used by "mere mortals" without calling setName(String name).

Therefore, to appease the Gods, a common pattern is to use a default test case name in this constructor and invoke the given name constructor afterwards:

public class MyTestCase extends TestCase {
   public MyTestCase() {
      this("MyTestCase Default Name");
   }

   public MyTestCase(String name...

The AndroidTestCase base class


This class can be used as a base class for general-purpose Android test cases.

Use it when you need access to Android resources, databases, or files in the filesystem. Context is stored as a field in this class, which is conveniently named mContext and can be used inside the tests if needed, or the getContext() method can be used too.

Tests based on this class can start more than one Activity using Context.startActivity().

There are various test cases in Android SDK that extend this base class:

  • ApplicationTestCase<T extends Application>

  • ProviderTestCase2<T extends ContentProvider>

  • ServiceTestCase<T extends Service>

When using the AndroidTestCase Java class, you inherit some base assertion methods that can be used; let's look at these in more detail.

The assertActivityRequiresPermission() method

The signature for this method is as follows:

public void assertActivityRequiresPermission(String packageName, String className, String permission)

Description...

Instrumentation


Instrumentation is instantiated by the system before any of the application code is run, thereby allowing monitoring of all the interactions between the system and the application.

As with many other Android application components, instrumentation implementations are described in the AndroidManifest.xml under the tag <instrumentation>. However, with the advent of Gradle, this has now been automated for us, and we can change the properties of the instrumentation in the app's build.gradle file. The AndroidManifest file for your tests will be automatically generated:

defaultConfig {
  testApplicationId 'com.blundell.tut.tests'
testInstrumentationRunner  "android.test.InstrumentationTestRunner"
}

The values mentioned in the preceding code are also the defaults if you do not declare them, meaning that you don't have to have any of these parameters to start writing tests.

The testApplicationId attribute defines the name of the package for your tests. As a default, it is your...

The InstrumentationTestCase class


The InstrumentationTestCase class is the direct or indirect base class for various test cases that have access to Instrumentation. This is the list of the most important direct and indirect subclasses:

  • ActivityTestCase

  • ProviderTestCase2<T extends ContentProvider>

  • SingleLaunchActivityTestCase<T extends Activity>

  • SyncBaseInstrumentation

  • ActivityInstrumentationTestCase2<T extends Activity>

  • ActivityUnitTestCase<T extends Activity>

The InstrumentationTestCase class is in the android.test package, and extends junit.framework.TestCase, which extends junit.framework.Assert.

The launchActivity and launchActivityWithIntent methods

These utility methods are used to launch Activities from a test. If the Intent is not specified using the second option, a default Intent is used:

public final T launchActivity (String pkg, Class<T> activityCls, Bundle extras)

Note

The template class parameter T is used in activityCls and as the return type...

The ActivityTestCase class


This is mainly a class that holds common code for other test cases that access Instrumentation.

You can use this class if you are implementing a specific behavior for test cases and the existing alternatives don't fit your requirements. This means you are unlikely to use this class unless you want to implement a new base class for other tests to use. For example, consider a scenario where Google brings out a new component and you want to write tests around it (like SuperNewContentProvider).

If this is not the case, you might find the following options more suitable for your requirements:

  • ActivityInstrumentationTestCase2<T extends Activity>

  • ActivityUnitTestCase<T extends Activity>

The abstract class android.test.ActivityTestCase extends android.test.InstrumentationTestCase and serves as a base class for other different test cases, such as android.test.ActivityInstrumentationTestCase, android.test.ActivityInstrumentationTestCase2, and android.test.ActivityUnitTestCase...

The ActivityInstrumentationTestCase2 class


The ActivityInstrumentationTestCase2 class would probably be the one you use the most to write functional Android test cases. It provides functional testing of a single Activity.

This class has access to Instrumentation and will create the Activity under test using the system infrastructure, by calling InstrumentationTestCase.launchActivity(). The Activity can then be manipulated and monitored after creation.

If you need to provide a custom Intent to start your Activity, before invoking getActivity(), you may inject an Intent with setActivityIntent(Intent intent).

This test case would be very useful to test interactions through the user interface as events can be injected to simulate user behavior.

The constructor

There is only one public non-deprecated constructor for this class, which is as follows:

ActivityInstrumentationTestCase2(Class<T> activityClass)

It should be invoked with an instance of the Activity class for the same Activity used as...

The ProviderTestCase2<T> class


This is a test case designed to test the ContentProvider classes.

The ProviderTestCase2 class also extends AndroidTestCase. The class template parameter T represents ContentProvider under test. Implementation of this test uses IsolatedContext and MockContentResolver, which are mock objects that we described before in this chapter.

The constructor

There is only one public non-deprecated constructor for this class. This is as follows:

ProviderTestCase2(Class<T> providerClass, String providerAuthority)

This should be invoked with an instance of the ContentProvider class for the same ContentProvider class used as a class template parameter.

The second parameter is the authority for the provider, which is usually defined as the AUTHORITY constant in the ContentProvider class.

An example

This is a typical example of a ContentProvider test:

public void testQuery() {
    String segment = "dummySegment";
    Uri uri = Uri.withAppendedPath(MyProvider.CONTENT_URI,...

The ServiceTestCase<T>


This is a test case specially created to test services. The methods to exercise the service life cycle, such as setupService, startService, bindService, and shutDownService, are also included in this class.

The constructor

There is only one public non-deprecated constructor for this class. This is as follows:

ServiceTestCase(Class<T> serviceClass)

It should be invoked with an instance of the Service class for the same Service used as a class template parameter.

The TestSuiteBuilder.FailedToCreateTests class


The TestSuiteBuilder.FailedToCreateTests class is a special TestCase class used to indicate a failure during the build() step. That is, during the test suite creation, if an error is detected, you will receive an exception like this one, which indicates the failure to construct the test suite:

INFO/TestRunner(1): java.lang.RuntimeException: Exception during suite construction
INFO/TestRunner(1):     at android.test.suitebuilder.TestSuiteBuilder$FailedToCreateTests.testSuiteConstructionFailed(TestSuiteBuilder.java:239)
INFO/TestRunner(1):     at java.lang.reflect.Method.invokeNative(Native Method)
[...]
INFO/TestRunner(1):     at android.test.InstrumentationTestRunner.onStart(InstrumentationTestRunner.java:520)
INFO/TestRunner(1):     at android.app.Instrumentation$InstrumentationThread.run(Instrumentation.java:1447)

Using libraries in test projects


Your Android project might require an external Java library or an Android library. Now, we will explain how to incorporate these in your project that is ready to be tested. Note that the following explains the usage of a local module that is an Android library, but the same rules can be applied to an external JAR (Java library) file or an external AAR (Android library) file.

Let's pretend that in one Activity, we are creating objects from a class that is part of a library. For the sake of our example, let's say the library is called dummyLibrary, and the mentioned class is Dummy.

So our Activity would look like this:

import com.blundell.dummylibrary.Dummy;

public class MyFirstProjectActivity extends Activity {
    private Dummy dummy;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        final EditText messageInput = (EditText) findViewById(R...

Summary


We investigated the most relevant building blocks and reusable patterns to create our tests. Along this journey, we:

  • Understood the common assertions found in JUnit tests

  • Explained the specialized assertions found in the Android SDK

  • Explored Android mock objects and their use in Android tests

  • Exemplified the use of the different test cases available in the Android SDK

Now that we have all the building blocks, it is time to start creating more and more tests to acquire the experience needed to master the technique.

The next chapter will provide you with examples of when and where to use different test cases on Android. This will give us a great breadth of expertise in knowing what testing methodology to apply when we have a specific scenario to test.

Left arrow icon Right arrow icon

What You Will Learn

Who Is This Book For?

If you are an Android developer looking to test your applications or optimize your application development process, then this book is for you. No previous experience in application testing is required.

Book Description

If you are an Android developer looking to test your applications or optimize your application development process, then this book is for you. No previous experience in application testing is required.
Category:
Languages:
Concepts:
Tools:

Frequently bought together


Stars icon
Total $ 148.97
Gradle for Android
$38.99
Learning Android Application Testing
$54.99
Asynchronous Android Programming
$54.99
Total $ 148.97 Stars icon

Table of Contents

(9 Chapters)
Getting Started with Testing Chevron down icon Chevron up icon
Understanding Testing with the Android SDK Chevron down icon Chevron up icon
Baking with Testing Recipes Chevron down icon Chevron up icon
Managing Your Android Testing Environment Chevron down icon Chevron up icon
Discovering Continuous Integration Chevron down icon Chevron up icon
Practicing Test-driven Development Chevron down icon Chevron up icon
Behavior-driven Development Chevron down icon Chevron up icon
Testing and Profiling Performance Chevron down icon Chevron up icon
Alternative Testing Tactics Chevron down icon Chevron up icon

Customer reviews

Rating distribution
Full star icon Full star icon Full star icon Half star icon Empty star icon
3.8
(4 Ratings)
5 star 25%
4 star 50%
3 star 0%
2 star 25%
1 star 0%
Rob Davies Apr 04, 2016
Full star icon Full star icon Full star icon Full star icon Full star icon
5
Saved me a lot of time researching.
Amazon Verified review Amazon
alf_biker Jun 06, 2017
Full star icon Full star icon Full star icon Full star icon Empty star icon
4
Provides a good starting point for doing android testing with Android Studio.
Amazon Verified review Amazon
Jinu Apr 13, 2017
Full star icon Full star icon Full star icon Full star icon Empty star icon
4
Good book to start but it does not have substantial code in it for absolute beginners to understand.And the testing Framework used in this book is currently deprecated.
Amazon Verified review Amazon
Jimi Damon Jul 15, 2016
Full star icon Full star icon Empty star icon Empty star icon Empty star icon
2
I bought this book hoping that I could apply some android testing techniques to some of the apps that I build for work. What I found is a book that , perhaps to no fault of the authors, hasn't caught up with Google's perpetually ( and nauseatingly ) changing Gradle infrastructure combined with AndroidStudio. So, what happens is that when you try to download their samples off of Packet Publishing is that you get source code that barely works. For instance, a number of their example JUnit tests completely fail because permissions weren't set correctly in an AndroidManifest file . This isn't really entirely the authors' fault because Google has been screwing with this for the last 5 years or so. But there are other issues as well. The book doesn't give you good instruction on how to set up any of the advanced testing they are doing by way of Android Studio. As anyone who is doing Android programming, Android Studio is considered both the solution and cause of every problem related to Android . Hence, if you write a book explaining how to do something with Android and you don't provide some examples that show you how to say enable permissions for a Junit test for modifying bookmars from within Android Studio, you are doing your readers a disservice.I found that the book just mentions a bunch of types of tests you can use , something you could learn from any other book on testing software, but offers no real good or working examples of how to use those techniques to test the Android UI or an App's services...etc.
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

How do I buy and download an eBook? Chevron down icon Chevron up icon

Where there is an eBook version of a title available, you can buy it from the book details for that title. Add either the standalone eBook or the eBook and print book bundle to your shopping cart. Your eBook will show in your cart as a product on its own. After completing checkout and payment in the normal way, you will receive your receipt on the screen containing a link to a personalised PDF download file. This link will remain active for 30 days. You can download backup copies of the file by logging in to your account at any time.

If you already have Adobe reader installed, then clicking on the link will download and open the PDF file directly. If you don't, then save the PDF file on your machine and download the Reader to view it.

Please Note: Packt eBooks are non-returnable and non-refundable.

Packt eBook and Licensing When you buy an eBook from Packt Publishing, completing your purchase means you accept the terms of our licence agreement. Please read the full text of the agreement. In it we have tried to balance the need for the ebook to be usable for you the reader with our needs to protect the rights of us as Publishers and of our authors. In summary, the agreement says:

  • You may make copies of your eBook for your own use onto any machine
  • You may not pass copies of the eBook on to anyone else
How can I make a purchase on your website? Chevron down icon Chevron up icon

If you want to purchase a video course, eBook or Bundle (Print+eBook) please follow below steps:

  1. Register on our website using your email address and the password.
  2. Search for the title by name or ISBN using the search option.
  3. Select the title you want to purchase.
  4. Choose the format you wish to purchase the title in; if you order the Print Book, you get a free eBook copy of the same title. 
  5. Proceed with the checkout process (payment to be made using Credit Card, Debit Cart, or PayPal)
Where can I access support around an eBook? Chevron down icon Chevron up icon
  • If you experience a problem with using or installing Adobe Reader, the contact Adobe directly.
  • To view the errata for the book, see www.packtpub.com/support and view the pages for the title you have.
  • To view your account details or to download a new copy of the book go to www.packtpub.com/account
  • To contact us directly if a problem is not resolved, use www.packtpub.com/contact-us
What eBook formats do Packt support? Chevron down icon Chevron up icon

Our eBooks are currently available in a variety of formats such as PDF and ePubs. In the future, this may well change with trends and development in technology, but please note that our PDFs are not Adobe eBook Reader format, which has greater restrictions on security.

You will need to use Adobe Reader v9 or later in order to read Packt's PDF eBooks.

What are the benefits of eBooks? Chevron down icon Chevron up icon
  • You can get the information you need immediately
  • You can easily take them with you on a laptop
  • You can download them an unlimited number of times
  • You can print them out
  • They are copy-paste enabled
  • They are searchable
  • There is no password protection
  • They are lower price than print
  • They save resources and space
What is an eBook? Chevron down icon Chevron up icon

Packt eBooks are a complete electronic version of the print edition, available in PDF and ePub formats. Every piece of content down to the page numbering is the same. Because we save the costs of printing and shipping the book to you, we are able to offer eBooks at a lower cost than print editions.

When you have purchased an eBook, simply login to your account and click on the link in Your Download Area. We recommend you saving the file to your hard drive before opening it.

For optimal viewing of our eBooks, we recommend you download and install the free Adobe Reader version 9.

Modal Close icon

Loading shipping options...

Unable to load shipping costs. Please try again later.

Estimated Shipping Cost

Deliver to -
Modal Close icon
Modal Close icon