introduction to android        testing     a hands-on approach   Copyright (C) 2011 Diego Torres Milano All rights reserved
diego torres milano  android system engineer         flextronicshttp://dtmilano.blogspot.com   Copyright (C) 2011 Diego Tor...
“Never test the depth ofthe water with both feet.”                                                        -- Anonymous    ...
agendaandroid testing backgroundtest driven developmentcode coveragecontinuous integrationbehavior driven development     ...
operating systems                                                      July 2011         Android          150M            ...
android testing  backgroundCopyright (C) 2011 Diego Torres Milano All rights reserved
?Copyright (C) 2011 Diego Torres Milano All rights reserved
Why                                                ?Copyright (C) 2011 Diego Torres Milano All rights reserved
What Why                                                 ? Copyright (C) 2011 Diego Torres Milano All rights reserved
What WhyWhen                                             ? Copyright (C) 2011 Diego Torres Milano All rights reserved
What WhyWhen  how                                                 ? Copyright (C) 2011 Diego Torres Milano All rights rese...
types of test                            testsunit                                                           functionalper...
types of testunit       Copyright (C) 2011 Diego Torres Milano All rights reserved
types of test                       by programmers for programmersunit       Copyright (C) 2011 Diego Torres Milano All ri...
types of test                       by programmers for programmersunit                       in a programming language    ...
types of test                       by programmers for programmersunit                       in a programming language    ...
types of test                       by programmers for programmersunit                       in a programming language    ...
types of test                       by programmers for programmersunit                       in a programming language    ...
types of test                       by programmers for programmersunit                       in a programming language    ...
types of test                            testsunit                                                           functionalper...
types of test                                                 functionalCopyright (C) 2011 Diego Torres Milano All rights ...
types of testby business & QA people                                   functional         Copyright (C) 2011 Diego Torres ...
types of testby business & QA people                                    functionalin a business domain language          C...
types of testby business & QA people                                    functionalin a business domain languagetest comple...
types of testby business & QA people                                    functionalin a business domain languagetest comple...
types of testby business & QA people                                    functionalin a business domain languagetest comple...
types of test                            testsunit                                                           functionalper...
types of test                                                 integrationCopyright (C) 2011 Diego Torres Milano All rights...
types of testhow components work together                              integration         Copyright (C) 2011 Diego Torres...
types of testhow components work together                              integrationmodules have been unit tested         Co...
types of testhow components work together                              integrationmodules have been unit testedandroid com...
types of testhow components work together                               integrationmodules have been unit testedandroid co...
types of test                            testsunit                                                           functionalper...
types of testperformance        Copyright (C) 2011 Diego Torres Milano All rights reserved
types of test                        measure performance in aperformance             repeatable way        Copyright (C) 2...
types of test                        measure performance in aperformance             repeatable way                       ...
types of test                        measure performance in aperformance             repeatable way                       ...
types of test                        measure performance in aperformance             repeatable way                       ...
types of test                            testsunit                                                           functionalper...
class diagram                                                                         Assert     <<iface>>                ...
InstrumentationTestCase            Copyright (C) 2011 Diego Torres Milano All rights reserved
InstrumentationTestCase                                            instrumentation instantiated                           ...
InstrumentationTestCase                                            instrumentation instantiated                           ...
InstrumentationTestCase                                            instrumentation instantiated                           ...
InstrumentationTestCase                                            instrumentation instantiated                           ...
InstrumentationTestCase                                            instrumentation instantiated                           ...
class diagram                                                                         Assert     <<iface>>                ...
ActivityUnitTestCase           Copyright (C) 2011 Diego Torres Milano All rights reserved
ActivityUnitTestCase                                           isolated testing of single                                 ...
ActivityUnitTestCase                                           isolated testing of single                                 ...
ActivityUnitTestCase                                           isolated testing of single                                 ...
ActivityUnitTestCase                                           isolated testing of single                                 ...
class diagram                                                                         Assert     <<iface>>                ...
ActivityInstrumentationTestCase2Copyright (C) 2011 Diego Torres Milano All rights reserved
ActivityInstrumentationTestCase2functionaltesting of a single Activity        Copyright (C) 2011 Diego Torres Milano All r...
ActivityInstrumentationTestCase2functionaltesting of a single Activityhas access to Instrumentation        Copyright (C) 2...
ActivityInstrumentationTestCase2functionaltesting of a single Activityhas access to Instrumentationcreates the AUT using s...
ActivityInstrumentationTestCase2functionaltesting of a single Activityhas access to Instrumentationcreates the AUT using s...
class diagram                                                                         Assert     <<iface>>                ...
AndroidTestCaseCopyright (C) 2011 Diego Torres Milano All rights reserved
access to Context                                  AndroidTestCase       Copyright (C) 2011 Diego Torres Milano All rights...
access to Context                                  AndroidTestCaseaccess to Resources       Copyright (C) 2011 Diego Torre...
access to Context                                   AndroidTestCaseaccess to Resourcesbase class for Application, Provider...
access to Context                                   AndroidTestCaseaccess to Resourcesbase class for Application, Provider...
access to Context                                   AndroidTestCaseaccess to Resourcesbase class for Application, Provider...
class diagram                                                                         Assert     <<iface>>                ...
test driven development    Copyright (C) 2011 Diego Torres Milano All rights reserved
test driven development                                      advantages:                                                  ...
test driven development                                        advantages:                                                ...
test driven development                                        advantages:                                                ...
test driven development                                        advantages:                                                ...
activity diagram                                                                design decisions are                      ...
temperature converter                         Title celsius                                                100            ...
requirementsCopyright (C) 2011 Diego Torres Milano All rights reserved
requirements     converts between temperature     units     one temperature is entered and     the other is updated     er...
understanding  requirementsCopyright (C) 2011 Diego Torres Milano All rights reserved
understanding       requirementsto write a test you must understand therequirement     Copyright (C) 2011 Diego Torres Mil...
understanding       requirementsto write a test you must understand therequirementdestination is quickly identified     Cop...
understanding       requirementsto write a test you must understand therequirementdestination is quickly identifiedif requi...
github$ mkdir myworkdir$ cd myworkdir$ git clone git@github.com:dtmilano/  TemperatureConverter.git$ git clone git://githu...
creating the main projectTemperatureConverter uses   conventional settings           Copyright (C) 2011 Diego Torres Milan...
creating the main projectTemperatureConverter uses   conventional settings           Copyright (C) 2011 Diego Torres Milan...
creating the test     projectAutomatically selected valuesfor TemperatureConverterTest           project             Copyr...
creating the test       case               Use:ActivityInstrumentationTestCase2        as the base classTemperatureConvert...
warning                                                                           due to the                              ...
constructor/**  * Constructor  * @param name  */public TemperatureConverterActivityTests(String name) {     super(Temperat...
fixtureprotected void setUp(String name) throws Exception {   super.setUp();    mActivity = getActivity();                 ...
layoutsatisfy the test needs             Copyright (C) 2011 Diego Torres Milano All rights reserved
ui tests: visibility@SmallTestpublic void testFieldsOnScreen() {   final View origin =           mActivity.getWindow().getD...
ui tests: alignment@SmallTestpublic void testAlignment() {! ! ViewAsserts.assertRightAligned(mCelsius,            mFahrenh...
ui tests: initialization@SmallTestpublic void testFieldsShouldStartEmpty() {! ! assertTrue("".equals(mCelsius.getText()   ...
ui tests: justification@SmallTestpublic void testJustification() {! ! final int expected =       Gravity.RIGHT|Gravity.CENTER...
running the tests                                                     video plays on                                      ...
running the tests                                                     video plays on                                      ...
gravity     add right andcenter_vertical gravity    for celsius and      fahrenheit          Copyright (C) 2011 Diego Torr...
gravity     add right andcenter_vertical gravity    for celsius and      fahrenheit          Copyright (C) 2011 Diego Torr...
running the tests                                                       video plays on                                    ...
running the tests                                                       video plays on                                    ...
temperature conversion!   @UiThreadTest!   public void testFahrenheitToCelsiusConversion() {!   ! mCelsius.clear();!   ! m...
temperature conversionrun in the ui!   @UiThreadTest             thread!   public void testFahrenheitToCelsiusConversion()...
temperature conversionrun in the ui!   @UiThreadTest             thread!   public void testFahrenheitToCelsiusConversion()...
temperature conversion run in the ui!   @UiThreadTest              thread!   public void testFahrenheitToCelsiusConversion...
EditNumber class  EditNumber class  extends EditText         Copyright (C) 2011 Diego Torres Milano All rights reserved
TemperatureCon    verterTemperatureConverter  is a helper class         Copyright (C) 2011 Diego Torres Milano All rights ...
exceptionjava.lang.ClassCastException:   android.widget.EditText at       com.example.i2at.tc.test.       TemperatureConve...
exceptionjava.lang.ClassCastException:   android.widget.EditText at       com.example.i2at.tc.test.       TemperatureConve...
layout<com.example.i2at.tc.EditNumber    android:layout_height="wrap_content"! ! android:layout_width="match_parent"    an...
running the tests Copyright (C) 2011 Diego Torres Milano All rights reserved
running the tests             what? Copyright (C) 2011 Diego Torres Milano All rights reserved
celsius to fahrenheit                                Fahrenheit 150112.5  75 37.5   0-37.5 -75        -40 -30 -20         ...
celsius to fahrenheit                                Fahrenheit 150112.5  75                       f = 9/5 * c + 32 37.5  ...
converterpublic class TemperatureConverter {! public static double fahrenheitToCelsius(double f) {	   / TODO Auto-generate...
TemperatureConv   erterTests   Test case as base class    create method stubs  TemperatureConverter as            CUT     ...
method stubsselect the methods you want      stubs created for            Copyright (C) 2011 Diego Torres Milano All right...
conversion testpublic void testFahrenheitToCelsius() {! ! for (double c: sConversionTableDouble.keySet()) {! ! ! final doub...
conversion tableprivate static final HashMap<Double, Double>         sConversionTableDouble =! ! !          new HashMap<Dou...
run the testsCopyright (C) 2011 Diego Torres Milano All rights reserved
run the tests                                                       this                                                  ...
creating test      caseuse AndroidTestCase as base           class  use EditNumber as CUT            Copyright (C) 2011 Di...
method stubsselect the Context constructor     select other methods             Copyright (C) 2011 Diego Torres Milano All...
testpublic final void testClear() {! ! final String value = "123.45";! ! mEditNumber.setText(value);! ! mEditNumber.clear();...
implementationpublic class EditNumber extends EditText {    / ...     /! public void clear() {! !   setText("");! }}      ...
testpublic final void testSetNumber() {! ! final double d = 123.45;! ! mEditNumber.setNumber(d);! ! final String expected = D...
testpublic final void testGetNumber() {! ! final double expected = 123.45;! ! mEditNumber.setNumber(expected);! ! final doubl...
implementationpublic class EditNumber extends EditText {    / ...     /!   public void getNumber() {       final String s =...
run the tests                                             NO videoCopyright (C) 2011 Diego Torres Milano All rights reserved
what’s the problem ?  Copyright (C) 2011 Diego Torres Milano All rights reserved
what’s the problem ?clear() worksrequestFocus() workssetNumber() worksfahrenheitToCelsius() worksgetNumber() worksso ?    ...
temperature converter                         Title celsius                                                100            ...
temperature converter                         Title celsius                                                100            ...
TemperatureChan   geWatcher  create it as an inner class   implements TextWatcher inherited abstract methods  create 2 fiel...
generateconstructor  use the fieldsomit call to super()        Copyright (C) 2011 Diego Torres Milano All rights reserved
the watcherpublic abstract class TemperatureChangeWatcher           implements TextWatcher {! ! private EditNumber mSource...
on text changed@Overridepublic void onTextChanged(CharSequence s, int start, int before, int count) {! if ( !mDest.hasWind...
on text changed@Overridepublic void onTextChanged(CharSequence s, int start, int before, int count) {! if ( !mDest.hasWind...
abstract convert methodpublic abstract class TemperatureChangeWatcher       implements TextWatcher {  //...    protected a...
find views@Overridepublic void onCreate(Bundle savedInstanceState) {    super.onCreate(savedInstanceState);    setContentVi...
add change listeners@Overridepublic void onCreate(Bundle savedInstanceState) {   / ...    /   mCelsius.addTextChangedListe...
add conversionpublic class TemperatureConverter {! public static double fahrenheitToCelsius(double f) {! ! return (f-32) *...
adding testpublic class TemperatureConverterTests extends TestCase {   / ...    /! /**! * Test method for {@link Temperatu...
running the tests Copyright (C) 2011 Diego Torres Milano All rights reserved
implementing conversionpublic class TemperatureConverter {! public static double fahrenheitToCelsius(double f) {! ! return...
running the tests Copyright (C) 2011 Diego Torres Milano All rights reserved
code coverageCopyright (C) 2011 Diego Torres Milano All rights reserved
code coverageCopyright (C) 2011 Diego Torres Milano All rights reserved
code coveragemeasures the amount of source code tested     Copyright (C) 2011 Diego Torres Milano All rights reserved
code coveragemeasures the amount of source code testedandroid relies on emma (http://emma.sf.net)      Copyright (C) 2011 ...
code coveragemeasures the amount of source code testedandroid relies on emma (http://emma.sf.net)supported coverage types:...
coverage reportCopyright (C) 2011 Diego Torres Milano All rights reserved
coverage reportoverall coverage summary     Copyright (C) 2011 Diego Torres Milano All rights reserved
coverage reportoverall coverage summaryoverall stats summary     Copyright (C) 2011 Diego Torres Milano All rights reserved
coverage reportoverall coverage summaryoverall stats summarycoverage breakdown by package     Copyright (C) 2011 Diego Tor...
building with antdisable project’s Build Automatically in Eclipseconvert project to ant$ android update project --path $PW...
run configuration                                          coveragerun build.xml as Ant build...   use coverage target     ...
ant 1.8specify ant 1.8 home                                                 Ant home...          Copyright (C) 2011 Diego ...
coveragerun build.xml coveragecoverage analysis report is generatedget coverage file$ adb pull /data/data/com.example.i2at....
coverage reportCopyright (C) 2011 Diego Torres Milano All rights reserved
coverage reportCopyright (C) 2011 Diego Torres Milano All rights reserved
importing  coverage fileimport the coverage session        into Eclipse             Copyright (C) 2011 Diego Torres Milano ...
coverage     sessionselect the project folders            Copyright (C) 2011 Diego Torres Milano All rights reserved
convert not covered  Copyright (C) 2011 Diego Torres Milano All rights reserved
adding missing test@UiThreadTestpublic void testCelsiusToFahrenheitConversion() {   ! mCelsius.clear();! ! mFahrenheit.cle...
coverageCopyright (C) 2011 Diego Torres Milano All rights reserved
constructor not covered    Copyright (C) 2011 Diego Torres Milano All rights reserved
private constructorpublic class TemperatureConverter {! private TemperatureConverter() {! ! / do nothing     /! }! public ...
access private                 constructorpublic final void testPrivateConstructor() throws SecurityException,         NoSu...
access private                 constructorpublic final void testPrivateConstructor() throws SecurityException,         NoSu...
coverage reportCopyright (C) 2011 Diego Torres Milano All rights reserved
finished applicationthis is the final result          Copyright (C) 2011 Diego Torres Milano All rights reserved
requirements     converts between temperature     units     one temperature is entered and     the other is updated     er...
continuous integration   Copyright (C) 2011 Diego Torres Milano All rights reserved
continuous integrationagile technique for software engineeringreceived broad adoption in recent yearsprevents “integration...
requirementsversion control systemautomated buildself testedartifacts and tests results easy to find     Copyright (C) 2011...
installationdownload war from http://hudson-ci.org$ java -jar hudson.war       Copyright (C) 2011 Diego Torres Milano All ...
hudson homeCopyright (C) 2011 Diego Torres Milano All rights reserved
android pluginCopyright (C) 2011 Diego Torres Milano All rights reserved
android sdk rootCopyright (C) 2011 Diego Torres Milano All rights reserved
new jobCopyright (C) 2011 Diego Torres Milano All rights reserved
ant propertiesCopyright (C) 2011 Diego Torres Milano All rights reserved
build artifactsCopyright (C) 2011 Diego Torres Milano All rights reserved
build dependency                                               these are the                                              ...
android emulatorCopyright (C) 2011 Diego Torres Milano All rights reserved
android emulatorCopyright (C) 2011 Diego Torres Milano All rights reserved
build with antCopyright (C) 2011 Diego Torres Milano All rights reserved
xml test resultsdownload xmlinstrumentationtestrunner.jarreplace instrumentation byandroid:name="com.neenbedankt.android.t...
junit test resultCopyright (C) 2011 Diego Torres Milano All rights reserved
test reportCopyright (C) 2011 Diego Torres Milano All rights reserved
behavior driven developmentCopyright (C) 2011 Diego Torres Milano All rights reserved
behavior driven      developmentevolution of Test Driven Developmentinclusion of business participantcommon vocabularybase...
fitnesseCopyright (C) 2011 Diego Torres Milano All rights reserved
test suiteCopyright (C) 2011 Diego Torres Milano All rights reserved
slim test fixturepackage com.example.i2at.tc.test.fitnesse.fixture;import com.example.i2at.tc.TemperatureConverter;public cla...
test runCopyright (C) 2011 Diego Torres Milano All rights reserved
questions ?Copyright (C) 2011 Diego Torres Milano All rights reserved
android application  testing guide Copyright (C) 2011 Diego Torres Milano All rights reserved
android application          testing guide  Apply testing techniques and tools• Learn the nuances of Unit and  Functional ...
thank youCopyright (C) 2011 Diego Torres Milano All rights reserved
Upcoming SlideShare
Loading in...5
×

Introduction to android testing

53,369

Published on

Tutorial presented at LinuxCon 2011 North America (Vancouver, BC, Canada)

Published in: Technology
3 Comments
41 Likes
Statistics
Notes
No Downloads
Views
Total Views
53,369
On Slideshare
0
From Embeds
0
Number of Embeds
56
Actions
Shares
0
Downloads
1,297
Comments
3
Likes
41
Embeds 0
No embeds

No notes for slide
  • \n
  • \n
  • \n
  • \n
  • Google CEO Larry Page&amp;#x2019;s blog post announcing the news: Android now has a total of over 150 million activated devices worldwide. That number is up from 130 million handsets only a month ago. And they continue to sell at a rate of over 550,000 new activations a day (this stat had been previously announced). To add some context, Apple announced last month that it&amp;#x2019;s sold 222 million iOS devices to date, including the iPod Touch, iPad, and iPhone.\n
  • We will be reviewing the main concepts behind testing and the techniques, frameworks, and tools available to deploy your testing strategy on Android.\nInitially, when Android was introduced by the end of 2007, there was very little support for testing on the platform, but with the latests SDK versions a complete test framework was introduced.\n\n
  • why: because bugs severely affect projects, killing them early saves project resources, also to grasp requirements\nwhat: the more you cover higher the expectations of finding bugs, coverage analysis helps\nwhen: the sooner the better, TDD, an agile component, helps in this area and forces you to face bugs earlier\nhow: applying the techniques and tools we will be revealing soon\n
  • why: because bugs severely affect projects, killing them early saves project resources, also to grasp requirements\nwhat: the more you cover higher the expectations of finding bugs, coverage analysis helps\nwhen: the sooner the better, TDD, an agile component, helps in this area and forces you to face bugs earlier\nhow: applying the techniques and tools we will be revealing soon\n
  • why: because bugs severely affect projects, killing them early saves project resources, also to grasp requirements\nwhat: the more you cover higher the expectations of finding bugs, coverage analysis helps\nwhen: the sooner the better, TDD, an agile component, helps in this area and forces you to face bugs earlier\nhow: applying the techniques and tools we will be revealing soon\n
  • why: because bugs severely affect projects, killing them early saves project resources, also to grasp requirements\nwhat: the more you cover higher the expectations of finding bugs, coverage analysis helps\nwhen: the sooner the better, TDD, an agile component, helps in this area and forces you to face bugs earlier\nhow: applying the techniques and tools we will be revealing soon\n
  • Testing can be implemented at any time in the development process. However, we will be promoting testing at an early stage of the development effort, even before the full set of requirements have been defined and the coding process has been started.\nThere are several types of test available depending on the object being tested. Regardless of its type, a test should verify a condition and return the result of this evaluation as a single Boolean value indicating success or failure.\n\n
  • Unit tests are software tests written by programmers for programmers in a programming language and they should isolate the component under test and be able to test it in a repeatable way.\n\n
  • Unit tests are software tests written by programmers for programmers in a programming language and they should isolate the component under test and be able to test it in a repeatable way.\n\n
  • Unit tests are software tests written by programmers for programmers in a programming language and they should isolate the component under test and be able to test it in a repeatable way.\n\n
  • Unit tests are software tests written by programmers for programmers in a programming language and they should isolate the component under test and be able to test it in a repeatable way.\n\n
  • Unit tests are software tests written by programmers for programmers in a programming language and they should isolate the component under test and be able to test it in a repeatable way.\n\n
  • Unit tests are software tests written by programmers for programmers in a programming language and they should isolate the component under test and be able to test it in a repeatable way.\n\n
  • Android (up to Android 2.3 Gingerbread) uses JUnit 3. This version doesn&apos;t use annotations and uses introspection to detect the tests.\n\n
  • In agile software development, functional or acceptance tests are usually created by business and Quality Assurance (QA) people and expressed in a business domain language. These are high level tests to test the completeness and correctness of a user requirement or feature.\nWe will be introducing FitNesse, a framework that can be integrated \n\n
  • In agile software development, functional or acceptance tests are usually created by business and Quality Assurance (QA) people and expressed in a business domain language. These are high level tests to test the completeness and correctness of a user requirement or feature.\nWe will be introducing FitNesse, a framework that can be integrated \n\n
  • In agile software development, functional or acceptance tests are usually created by business and Quality Assurance (QA) people and expressed in a business domain language. These are high level tests to test the completeness and correctness of a user requirement or feature.\nWe will be introducing FitNesse, a framework that can be integrated \n\n
  • In agile software development, functional or acceptance tests are usually created by business and Quality Assurance (QA) people and expressed in a business domain language. These are high level tests to test the completeness and correctness of a user requirement or feature.\nWe will be introducing FitNesse, a framework that can be integrated \n\n
  • In agile software development, functional or acceptance tests are usually created by business and Quality Assurance (QA) people and expressed in a business domain language. These are high level tests to test the completeness and correctness of a user requirement or feature.\nWe will be introducing FitNesse, a framework that can be integrated \n\n
  • \n
  • Integration tests are designed to test the way individual components work jointly. Modules that have been unit tested independently are now combined together to test the integration.\nUsually Android Activities require some integration with the system infrastructure to be able to run. They need the Activity lifecycle provided by the ActivityManager, and access to resources, filesystem, and databases.\n\n
  • Integration tests are designed to test the way individual components work jointly. Modules that have been unit tested independently are now combined together to test the integration.\nUsually Android Activities require some integration with the system infrastructure to be able to run. They need the Activity lifecycle provided by the ActivityManager, and access to resources, filesystem, and databases.\n\n
  • Integration tests are designed to test the way individual components work jointly. Modules that have been unit tested independently are now combined together to test the integration.\nUsually Android Activities require some integration with the system infrastructure to be able to run. They need the Activity lifecycle provided by the ActivityManager, and access to resources, filesystem, and databases.\n\n
  • Integration tests are designed to test the way individual components work jointly. Modules that have been unit tested independently are now combined together to test the integration.\nUsually Android Activities require some integration with the system infrastructure to be able to run. They need the Activity lifecycle provided by the ActivityManager, and access to resources, filesystem, and databases.\n\n
  • \n
  • And finally, Performance tests measure performance characteristics of the components in a repeatable way.\nAs is widely known, premature optimization does more harm than good, so it is better to clearly understand the impact of your changes on the overall performance.\n\n
  • And finally, Performance tests measure performance characteristics of the components in a repeatable way.\nAs is widely known, premature optimization does more harm than good, so it is better to clearly understand the impact of your changes on the overall performance.\n\n
  • And finally, Performance tests measure performance characteristics of the components in a repeatable way.\nAs is widely known, premature optimization does more harm than good, so it is better to clearly understand the impact of your changes on the overall performance.\n\n
  • And finally, Performance tests measure performance characteristics of the components in a repeatable way.\nAs is widely known, premature optimization does more harm than good, so it is better to clearly understand the impact of your changes on the overall performance.\n\n
  • Android provides a very advanced testing framework extending the industry standard JUnit with specific features suitable for implementing all of the testing strategies and types we mentioned before.\n\n
  • \n
  • Yellow: junit Green: android\n\n
  • The instrumentation framework is the foundation of the testing framework. Instrumentation controls the application under test and permits the injection of mock components required by the application to run. For example, you can create mock Contexts before the application starts and let the application use them.\nHas launchActivity and launchActivityWithIntent utility methods.\n
  • The instrumentation framework is the foundation of the testing framework. Instrumentation controls the application under test and permits the injection of mock components required by the application to run. For example, you can create mock Contexts before the application starts and let the application use them.\nHas launchActivity and launchActivityWithIntent utility methods.\n
  • The instrumentation framework is the foundation of the testing framework. Instrumentation controls the application under test and permits the injection of mock components required by the application to run. For example, you can create mock Contexts before the application starts and let the application use them.\nHas launchActivity and launchActivityWithIntent utility methods.\n
  • The instrumentation framework is the foundation of the testing framework. Instrumentation controls the application under test and permits the injection of mock components required by the application to run. For example, you can create mock Contexts before the application starts and let the application use them.\nHas launchActivity and launchActivityWithIntent utility methods.\n
  • The instrumentation framework is the foundation of the testing framework. Instrumentation controls the application under test and permits the injection of mock components required by the application to run. For example, you can create mock Contexts before the application starts and let the application use them.\nHas launchActivity and launchActivityWithIntent utility methods.\n
  • All interaction of the application with the surrounding environment can be controlled using this approach. You can also isolate your application in a restricted environment to be able to predict the results, forcing the values returned by some methods or mocking persistent and unchanged data for ContentProvider, databases, or even the filesystem content.\n
  • The following methods should not be called in this configuration - most of them will throw exceptions:\nstartActivityIfNeeded(), getCallingActivity(), getTaskId(), moveTaskToBack()\n\n
  • The following methods should not be called in this configuration - most of them will throw exceptions:\nstartActivityIfNeeded(), getCallingActivity(), getTaskId(), moveTaskToBack()\n\n
  • The following methods should not be called in this configuration - most of them will throw exceptions:\nstartActivityIfNeeded(), getCallingActivity(), getTaskId(), moveTaskToBack()\n\n
  • The following methods should not be called in this configuration - most of them will throw exceptions:\nstartActivityIfNeeded(), getCallingActivity(), getTaskId(), moveTaskToBack()\n\n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • This class can be used as a base class for general purpose Android test cases.\nUse this class when you need access to an Activity Context like Resources, databases, or files in the filesystem. Context is stored as a field in this class conveniently named mContext and can be used inside the tests if needed.\nTests based on this class can start more than one Activity using Context.startActivity().\n\n
  • This class can be used as a base class for general purpose Android test cases.\nUse this class when you need access to an Activity Context like Resources, databases, or files in the filesystem. Context is stored as a field in this class conveniently named mContext and can be used inside the tests if needed.\nTests based on this class can start more than one Activity using Context.startActivity().\n\n
  • This class can be used as a base class for general purpose Android test cases.\nUse this class when you need access to an Activity Context like Resources, databases, or files in the filesystem. Context is stored as a field in this class conveniently named mContext and can be used inside the tests if needed.\nTests based on this class can start more than one Activity using Context.startActivity().\n\n
  • This class can be used as a base class for general purpose Android test cases.\nUse this class when you need access to an Activity Context like Resources, databases, or files in the filesystem. Context is stored as a field in this class conveniently named mContext and can be used inside the tests if needed.\nTests based on this class can start more than one Activity using Context.startActivity().\n\n
  • This class can be used as a base class for general purpose Android test cases.\nUse this class when you need access to an Activity Context like Resources, databases, or files in the filesystem. Context is stored as a field in this class conveniently named mContext and can be used inside the tests if needed.\nTests based on this class can start more than one Activity using Context.startActivity().\n\n
  • \n
  • \n
  • Briefly, Test Driven Development is the strategy of writing tests along the development process. These test cases are written in advance of the code that is supposed to satisfy them.\nThis contrasts with other approaches to the development process where the tests are written at the end when all the coding has been done.\n\n
  • Briefly, Test Driven Development is the strategy of writing tests along the development process. These test cases are written in advance of the code that is supposed to satisfy them.\nThis contrasts with other approaches to the development process where the tests are written at the end when all the coding has been done.\n\n
  • Briefly, Test Driven Development is the strategy of writing tests along the development process. These test cases are written in advance of the code that is supposed to satisfy them.\nThis contrasts with other approaches to the development process where the tests are written at the end when all the coding has been done.\n\n
  • Design decisions are taken in single steps and finally the code satisfying the tests is improved by refactoring it.\nWe start our development process with writing a test case. This apparently simple process will put some machinery to work inside our heads.\n\n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • The main advantage I&apos;ve seen so far is that you focus your destination quickly and is much difficult to divert implementing options in your software that will never be used.\nTest Driven Development could not be indiscriminately applied to any project. I think that, as well as any other technique you should use your judgment and expertise to recognize where it can be applied.\n\n\n
  • The main advantage I&apos;ve seen so far is that you focus your destination quickly and is much difficult to divert implementing options in your software that will never be used.\nTest Driven Development could not be indiscriminately applied to any project. I think that, as well as any other technique you should use your judgment and expertise to recognize where it can be applied.\n\n\n
  • The main advantage I&apos;ve seen so far is that you focus your destination quickly and is much difficult to divert implementing options in your software that will never be used.\nTest Driven Development could not be indiscriminately applied to any project. I think that, as well as any other technique you should use your judgment and expertise to recognize where it can be applied.\n\n\n
  • git read-only access.\nDon&amp;#x2019;t forget to adapt local.properties.template to suit your environment needs if using ant.\nImport into Eclipse.\n
  • Our examples will revolve around an extremely simple Android sample project. It doesn&apos;t try to show all the fancy Android features but focuses on testing and gradually building the application from the test, applying the concepts learned before.\n
  • The creation of the test project is displayed in this screenshot. All values will be selected for you based on your previous entries.\n\n
  • Proceed with creating the first test by selecting the main test package name com.example.aatg.tc.test in Eclipse&apos;s Package Explorer, and then right-click on it. Select New | JUnit Test Case.\nJUnit 3 is the version supported by Android. Always use this option.\n
  • We now notice that our automatically generated class has some errors we need to fix before running. Otherwise the errors will prevent the test from compiling.\nFirst we should add the missing imports, using the shortcut Shift+Ctrl+O.\nSecond, the problem we need to fix is the no argument constructor.\n\n
  • We can start creating our test fixture (well known state defined as a baseline) by populating the setUp method with the elements we need in our tests. Almost unavoidable, in this case, is the use of the Activity under test, so let&apos;s prepare for the situation and add it to the fixture.\nThe ActivityInstrumentationTestCase2.getActivity() method has a side effect. If the Activity under test is not running, it is started.\n\n
  • \n
  • \n
  • \n
  • \n
  • \n
  • Video plays on click &gt;&gt;&gt;\n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • We define convert as an abstract method, to invoke the corresponding convert method depending on the conversion needed\n
  • We will be creating anonymous classes when we assign the watchers\n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • Code coverage is a measure used in software testing that describes the amount of source code that was actually tested by the test suite and to what degree following some criteria.\n\n
  • Code coverage is a measure used in software testing that describes the amount of source code that was actually tested by the test suite and to what degree following some criteria.\n\n
  • Code coverage is a measure used in software testing that describes the amount of source code that was actually tested by the test suite and to what degree following some criteria.\n\n
  • overall summary: the summary for all classes\noverall stats summary: the statistics of the coverage (i.e. how many packages)\ncoverage breakdown: coverage for particular packages\n
  • overall summary: the summary for all classes\noverall stats summary: the statistics of the coverage (i.e. how many packages)\ncoverage breakdown: coverage for particular packages\n
  • overall summary: the summary for all classes\noverall stats summary: the statistics of the coverage (i.e. how many packages)\ncoverage breakdown: coverage for particular packages\n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • The original article was written by Martin Fowler back in 2000, and describes the experience of putting together Continuous Integration on a large software project.\nContinuous Integration has received a broad adoption in recent years, and a proliferation of commercial tools and Open Source projects is a clear demonstration of its success.\n\n
  • Continuous Integration is one agile technique for software engineering that aims to improve the software quality and to reduce the time taken to integrate changes by continuously applying integration and testing frequently, opposed to the more traditional approach of integrating and testing by the end of the development cycle.\n\n
  • The most common practice is to trigger the build process after every commit to the source code repository, this practice also implies other requirements, beside the source code being maintained by a Version Control System.\nBuilds should be automated by running a single command.\nThe build should be self tested,\n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • \n
  • Introduction to android testing

    1. 1. introduction to android testing a hands-on approach Copyright (C) 2011 Diego Torres Milano All rights reserved
    2. 2. diego torres milano android system engineer flextronicshttp://dtmilano.blogspot.com Copyright (C) 2011 Diego Torres Milano All rights reserved
    3. 3. “Never test the depth ofthe water with both feet.” -- Anonymous Copyright (C) 2011 Diego Torres Milano All rights reserved
    4. 4. agendaandroid testing backgroundtest driven developmentcode coveragecontinuous integrationbehavior driven development Copyright (C) 2011 Diego Torres Milano All rights reserved
    5. 5. operating systems July 2011 Android 150M iOS 222M Copyright (C) 2011 Diego Torres Milano All rights reserved
    6. 6. android testing backgroundCopyright (C) 2011 Diego Torres Milano All rights reserved
    7. 7. ?Copyright (C) 2011 Diego Torres Milano All rights reserved
    8. 8. Why ?Copyright (C) 2011 Diego Torres Milano All rights reserved
    9. 9. What Why ? Copyright (C) 2011 Diego Torres Milano All rights reserved
    10. 10. What WhyWhen ? Copyright (C) 2011 Diego Torres Milano All rights reserved
    11. 11. What WhyWhen how ? Copyright (C) 2011 Diego Torres Milano All rights reserved
    12. 12. types of test testsunit functionalperformance integration Copyright (C) 2011 Diego Torres Milano All rights reserved
    13. 13. types of testunit Copyright (C) 2011 Diego Torres Milano All rights reserved
    14. 14. types of test by programmers for programmersunit Copyright (C) 2011 Diego Torres Milano All rights reserved
    15. 15. types of test by programmers for programmersunit in a programming language Copyright (C) 2011 Diego Torres Milano All rights reserved
    16. 16. types of test by programmers for programmersunit in a programming language JUnit is the de-facto standard Copyright (C) 2011 Diego Torres Milano All rights reserved
    17. 17. types of test by programmers for programmersunit in a programming language JUnit is the de-facto standard test objects in isolation Copyright (C) 2011 Diego Torres Milano All rights reserved
    18. 18. types of test by programmers for programmersunit in a programming language JUnit is the de-facto standard test objects in isolation in a repeatable way Copyright (C) 2011 Diego Torres Milano All rights reserved
    19. 19. types of test by programmers for programmersunit in a programming language JUnit is the de-facto standard test objects in isolation in a repeatable way usually rely on mock objects Copyright (C) 2011 Diego Torres Milano All rights reserved
    20. 20. types of test testsunit functionalperformance integration Copyright (C) 2011 Diego Torres Milano All rights reserved
    21. 21. types of test functionalCopyright (C) 2011 Diego Torres Milano All rights reserved
    22. 22. types of testby business & QA people functional Copyright (C) 2011 Diego Torres Milano All rights reserved
    23. 23. types of testby business & QA people functionalin a business domain language Copyright (C) 2011 Diego Torres Milano All rights reserved
    24. 24. types of testby business & QA people functionalin a business domain languagetest completeness & correctness Copyright (C) 2011 Diego Torres Milano All rights reserved
    25. 25. types of testby business & QA people functionalin a business domain languagetest completeness & correctnessBDD has gained some popularity Copyright (C) 2011 Diego Torres Milano All rights reserved
    26. 26. types of testby business & QA people functionalin a business domain languagetest completeness & correctnessBDD has gained some popularityFitNesse can help Copyright (C) 2011 Diego Torres Milano All rights reserved
    27. 27. types of test testsunit functionalperformance integration Copyright (C) 2011 Diego Torres Milano All rights reserved
    28. 28. types of test integrationCopyright (C) 2011 Diego Torres Milano All rights reserved
    29. 29. types of testhow components work together integration Copyright (C) 2011 Diego Torres Milano All rights reserved
    30. 30. types of testhow components work together integrationmodules have been unit tested Copyright (C) 2011 Diego Torres Milano All rights reserved
    31. 31. types of testhow components work together integrationmodules have been unit testedandroid components need integrationwith the system Copyright (C) 2011 Diego Torres Milano All rights reserved
    32. 32. types of testhow components work together integrationmodules have been unit testedandroid components need integrationwith the systemtesting framework facilitatesintegration Copyright (C) 2011 Diego Torres Milano All rights reserved
    33. 33. types of test testsunit functionalperformance integration Copyright (C) 2011 Diego Torres Milano All rights reserved
    34. 34. types of testperformance Copyright (C) 2011 Diego Torres Milano All rights reserved
    35. 35. types of test measure performance in aperformance repeatable way Copyright (C) 2011 Diego Torres Milano All rights reserved
    36. 36. types of test measure performance in aperformance repeatable way if cannot be measure cannot be improved Copyright (C) 2011 Diego Torres Milano All rights reserved
    37. 37. types of test measure performance in aperformance repeatable way if cannot be measure cannot be improved premature optimization does more harm than good Copyright (C) 2011 Diego Torres Milano All rights reserved
    38. 38. types of test measure performance in aperformance repeatable way if cannot be measure cannot be improved premature optimization does more harm than good measure-change-measure Copyright (C) 2011 Diego Torres Milano All rights reserved
    39. 39. types of test testsunit functionalperformance integration Copyright (C) 2011 Diego Torres Milano All rights reserved
    40. 40. class diagram Assert <<iface>> TestCase Test InstrumentationTestCase AndroidTestCase ActivityInstrumentationTestCase2ActivityUnitTestCase Copyright (C) 2011 Diego Torres Milano All rights reserved
    41. 41. InstrumentationTestCase Copyright (C) 2011 Diego Torres Milano All rights reserved
    42. 42. InstrumentationTestCase instrumentation instantiated before application Copyright (C) 2011 Diego Torres Milano All rights reserved
    43. 43. InstrumentationTestCase instrumentation instantiated before application allows for monitoring interaction Copyright (C) 2011 Diego Torres Milano All rights reserved
    44. 44. InstrumentationTestCase instrumentation instantiated before application allows for monitoring interaction send keys and input events Copyright (C) 2011 Diego Torres Milano All rights reserved
    45. 45. InstrumentationTestCase instrumentation instantiated before application allows for monitoring interaction send keys and input events manual lifecycle Copyright (C) 2011 Diego Torres Milano All rights reserved
    46. 46. InstrumentationTestCase instrumentation instantiated before application allows for monitoring interaction send keys and input events manual lifecycle direct or indirect base class of other tests Copyright (C) 2011 Diego Torres Milano All rights reserved
    47. 47. class diagram Assert <<iface>> TestCase Test InstrumentationTestCase AndroidTestCase ActivityInstrumentationTestCase2ActivityUnitTestCase Copyright (C) 2011 Diego Torres Milano All rights reserved
    48. 48. ActivityUnitTestCase Copyright (C) 2011 Diego Torres Milano All rights reserved
    49. 49. ActivityUnitTestCase isolated testing of single Activity Copyright (C) 2011 Diego Torres Milano All rights reserved
    50. 50. ActivityUnitTestCase isolated testing of single Activity minimal connection to the system Copyright (C) 2011 Diego Torres Milano All rights reserved
    51. 51. ActivityUnitTestCase isolated testing of single Activity minimal connection to the system uses mocks for dependencies Copyright (C) 2011 Diego Torres Milano All rights reserved
    52. 52. ActivityUnitTestCase isolated testing of single Activity minimal connection to the system uses mocks for dependencies some Activity methods should not be called Copyright (C) 2011 Diego Torres Milano All rights reserved
    53. 53. class diagram Assert <<iface>> TestCase Test InstrumentationTestCase AndroidTestCase ActivityInstrumentationTestCase2ActivityUnitTestCase Copyright (C) 2011 Diego Torres Milano All rights reserved
    54. 54. ActivityInstrumentationTestCase2Copyright (C) 2011 Diego Torres Milano All rights reserved
    55. 55. ActivityInstrumentationTestCase2functionaltesting of a single Activity Copyright (C) 2011 Diego Torres Milano All rights reserved
    56. 56. ActivityInstrumentationTestCase2functionaltesting of a single Activityhas access to Instrumentation Copyright (C) 2011 Diego Torres Milano All rights reserved
    57. 57. ActivityInstrumentationTestCase2functionaltesting of a single Activityhas access to Instrumentationcreates the AUT using systeminfrastructure Copyright (C) 2011 Diego Torres Milano All rights reserved
    58. 58. ActivityInstrumentationTestCase2functionaltesting of a single Activityhas access to Instrumentationcreates the AUT using systeminfrastructurecustom intent can be provided Copyright (C) 2011 Diego Torres Milano All rights reserved
    59. 59. class diagram Assert <<iface>> TestCase Test InstrumentationTestCase AndroidTestCase ActivityInstrumentationTestCase2ActivityUnitTestCase Copyright (C) 2011 Diego Torres Milano All rights reserved
    60. 60. AndroidTestCaseCopyright (C) 2011 Diego Torres Milano All rights reserved
    61. 61. access to Context AndroidTestCase Copyright (C) 2011 Diego Torres Milano All rights reserved
    62. 62. access to Context AndroidTestCaseaccess to Resources Copyright (C) 2011 Diego Torres Milano All rights reserved
    63. 63. access to Context AndroidTestCaseaccess to Resourcesbase class for Application, Providerand Service test cases Copyright (C) 2011 Diego Torres Milano All rights reserved
    64. 64. access to Context AndroidTestCaseaccess to Resourcesbase class for Application, Providerand Service test casesContext stored in mContext field Copyright (C) 2011 Diego Torres Milano All rights reserved
    65. 65. access to Context AndroidTestCaseaccess to Resourcesbase class for Application, Providerand Service test casesContext stored in mContext fieldcan start more than one Activity Copyright (C) 2011 Diego Torres Milano All rights reserved
    66. 66. class diagram Assert <<iface>> TestCase Test InstrumentationTestCase AndroidTestCase ActivityInstrumentationTestCase2ActivityUnitTestCase Copyright (C) 2011 Diego Torres Milano All rights reserved
    67. 67. test driven development Copyright (C) 2011 Diego Torres Milano All rights reserved
    68. 68. test driven development advantages: •the tests are written one way or another •developers take more responsibility for the quality of their work Copyright (C) 2011 Diego Torres Milano All rights reserved
    69. 69. test driven development advantages: •the tests are written one way or another •developers take more responsibility for the quality of their work strategy of writing tests along development Copyright (C) 2011 Diego Torres Milano All rights reserved
    70. 70. test driven development advantages: •the tests are written one way or another •developers take more responsibility for the quality of their work strategy of writing tests along development test cases written prior to the code Copyright (C) 2011 Diego Torres Milano All rights reserved
    71. 71. test driven development advantages: •the tests are written one way or another •developers take more responsibility for the quality of their work strategy of writing tests along development test cases written prior to the code single test added, then the code to satisfy it Copyright (C) 2011 Diego Torres Milano All rights reserved
    72. 72. activity diagram design decisions are taken in single steps and finally the code write test satisfying the tests is improved by refactoring it run [fails] code[passes] refactor Copyright (C) 2011 Diego Torres Milano All rights reserved
    73. 73. temperature converter Title celsius 100 autoupdate 32fahrenheit keyboard Copyright (C) 2011 Diego Torres Milano All rights reserved
    74. 74. requirementsCopyright (C) 2011 Diego Torres Milano All rights reserved
    75. 75. requirements converts between temperature units one temperature is entered and the other is updated error is displayed in the field right aligned, 2 decimal digits entry fields start emptyCopyright (C) 2011 Diego Torres Milano All rights reserved
    76. 76. understanding requirementsCopyright (C) 2011 Diego Torres Milano All rights reserved
    77. 77. understanding requirementsto write a test you must understand therequirement Copyright (C) 2011 Diego Torres Milano All rights reserved
    78. 78. understanding requirementsto write a test you must understand therequirementdestination is quickly identified Copyright (C) 2011 Diego Torres Milano All rights reserved
    79. 79. understanding requirementsto write a test you must understand therequirementdestination is quickly identifiedif requirement change, changing thecorresponding test helps verify it Copyright (C) 2011 Diego Torres Milano All rights reserved
    80. 80. github$ mkdir myworkdir$ cd myworkdir$ git clone git@github.com:dtmilano/ TemperatureConverter.git$ git clone git://github.com/dtmilano/ TemperatureConverterTests.git Copyright (C) 2011 Diego Torres Milano All rights reserved
    81. 81. creating the main projectTemperatureConverter uses conventional settings Copyright (C) 2011 Diego Torres Milano All rights reserved
    82. 82. creating the main projectTemperatureConverter uses conventional settings Copyright (C) 2011 Diego Torres Milano All rights reserved
    83. 83. creating the test projectAutomatically selected valuesfor TemperatureConverterTest project Copyright (C) 2011 Diego Torres Milano All rights reserved
    84. 84. creating the test case Use:ActivityInstrumentationTestCase2 as the base classTemperatureConverterActivity as the class under test Copyright (C) 2011 Diego Torres Milano All rights reserved
    85. 85. warning due to the parameterized base classcreating the test case Use:ActivityInstrumentationTestCase2 as the base classTemperatureConverterActivity as the class under test Copyright (C) 2011 Diego Torres Milano All rights reserved
    86. 86. constructor/** * Constructor * @param name */public TemperatureConverterActivityTests(String name) { super(TemperatureConverterActivity.class); setName(name);} Copyright (C) 2011 Diego Torres Milano All rights reserved
    87. 87. fixtureprotected void setUp(String name) throws Exception { super.setUp(); mActivity = getActivity(); reference the assertNotNull(mActivity); main package mCelsius = (EditText)mActivity.findViewById(com...); assertNotNull(mCelsius); mFahrenheit = (EditText)mActivity.findViewById(com...); assertNotNull(mFahrenheit);} Copyright (C) 2011 Diego Torres Milano All rights reserved
    88. 88. layoutsatisfy the test needs Copyright (C) 2011 Diego Torres Milano All rights reserved
    89. 89. ui tests: visibility@SmallTestpublic void testFieldsOnScreen() { final View origin = mActivity.getWindow().getDecorView(); ViewAsserts.assertOnScreen(origin, mCelsius); ViewAsserts.assertOnScreen(origin, mFahrenheit);} Copyright (C) 2011 Diego Torres Milano All rights reserved
    90. 90. ui tests: alignment@SmallTestpublic void testAlignment() {! ! ViewAsserts.assertRightAligned(mCelsius, mFahrenheit);! ! ViewAsserts.assertLeftAligned(mCelsius, mFahrenheit);} Copyright (C) 2011 Diego Torres Milano All rights reserved
    91. 91. ui tests: initialization@SmallTestpublic void testFieldsShouldStartEmpty() {! ! assertTrue("".equals(mCelsius.getText() .toString()));! ! assertTrue("".equals(mFahrenheit.getText() .toString()));} Copyright (C) 2011 Diego Torres Milano All rights reserved
    92. 92. ui tests: justification@SmallTestpublic void testJustification() {! ! final int expected = Gravity.RIGHT|Gravity.CENTER_VERTICAL;! ! assertEquals(expected, mCelsius.getGravity());! ! assertEquals(expected, mFahrenheit.getGravity());} Copyright (C) 2011 Diego Torres Milano All rights reserved
    93. 93. running the tests video plays on click >>> Copyright (C) 2011 Diego Torres Milano All rights reserved
    94. 94. running the tests video plays on click >>> Copyright (C) 2011 Diego Torres Milano All rights reserved
    95. 95. gravity add right andcenter_vertical gravity for celsius and fahrenheit Copyright (C) 2011 Diego Torres Milano All rights reserved
    96. 96. gravity add right andcenter_vertical gravity for celsius and fahrenheit Copyright (C) 2011 Diego Torres Milano All rights reserved
    97. 97. running the tests video plays on click >>> Copyright (C) 2011 Diego Torres Milano All rights reserved
    98. 98. running the tests video plays on click >>> Copyright (C) 2011 Diego Torres Milano All rights reserved
    99. 99. temperature conversion! @UiThreadTest! public void testFahrenheitToCelsiusConversion() {! ! mCelsius.clear();! ! mFahrenheit.clear(); errors are underlined in red! ! final double f = 32.5;! ! mFahrenheit.requestFocus();! ! mFahrenheit.setNumber(f);! ! mCelsius.requestFocus();! ! final double expected = TemperatureConverter.fahrenheitToCelsius(f);! ! final double actual = mCelsius.getNumber();! ! final double delta = Math.abs(expected - actual);! ! assertTrue(delta < 0.005);! } Copyright (C) 2011 Diego Torres Milano All rights reserved
    100. 100. temperature conversionrun in the ui! @UiThreadTest thread! public void testFahrenheitToCelsiusConversion() {! ! mCelsius.clear();! ! mFahrenheit.clear(); errors are underlined in red! ! final double f = 32.5;! ! mFahrenheit.requestFocus();! ! mFahrenheit.setNumber(f);! ! mCelsius.requestFocus();! ! final double expected = TemperatureConverter.fahrenheitToCelsius(f);! ! final double actual = mCelsius.getNumber();! ! final double delta = Math.abs(expected - actual);! ! assertTrue(delta < 0.005);! } Copyright (C) 2011 Diego Torres Milano All rights reserved
    101. 101. temperature conversionrun in the ui! @UiThreadTest thread! public void testFahrenheitToCelsiusConversion() { specialized class! ! mCelsius.clear();! ! mFahrenheit.clear(); errors are underlined in red! ! final double f = 32.5;! ! mFahrenheit.requestFocus();! ! mFahrenheit.setNumber(f);! ! mCelsius.requestFocus();! ! final double expected = TemperatureConverter.fahrenheitToCelsius(f);! ! final double actual = mCelsius.getNumber();! ! final double delta = Math.abs(expected - actual);! ! assertTrue(delta < 0.005);! } Copyright (C) 2011 Diego Torres Milano All rights reserved
    102. 102. temperature conversion run in the ui! @UiThreadTest thread! public void testFahrenheitToCelsiusConversion() { specialized class! ! mCelsius.clear();! ! mFahrenheit.clear(); errors are underlined in red! ! final double f = 32.5;! ! mFahrenheit.requestFocus();! ! mFahrenheit.setNumber(f); converter! ! mCelsius.requestFocus(); helper! ! final double expected = TemperatureConverter.fahrenheitToCelsius(f);! ! final double actual = mCelsius.getNumber();! ! final double delta = Math.abs(expected - actual);! ! assertTrue(delta < 0.005);! } Copyright (C) 2011 Diego Torres Milano All rights reserved
    103. 103. EditNumber class EditNumber class extends EditText Copyright (C) 2011 Diego Torres Milano All rights reserved
    104. 104. TemperatureCon verterTemperatureConverter is a helper class Copyright (C) 2011 Diego Torres Milano All rights reserved
    105. 105. exceptionjava.lang.ClassCastException: android.widget.EditText at com.example.i2at.tc.test. TemperatureConverterActivityTests.setUp (TemperatureConverterActivityTests.java: 44) Copyright (C) 2011 Diego Torres Milano All rights reserved
    106. 106. exceptionjava.lang.ClassCastException: android.widget.EditText at com.example.i2at.tc.test. TemperatureConverterActivityTests.setUp (TemperatureConverterActivityTests.java: 44)44:!! mCelsius = (EditNumber) mActivity.findViewById( com.example.i2at.tc.R.id.celsius); Copyright (C) 2011 Diego Torres Milano All rights reserved
    107. 107. layout<com.example.i2at.tc.EditNumber android:layout_height="wrap_content"! ! android:layout_width="match_parent" android:inputType="numberDecimal"! ! android:id="@+id/celsius" android:gravity="right|center_vertical">! ! <requestFocus /></com.example.i2at.tc.EditNumber> Copyright (C) 2011 Diego Torres Milano All rights reserved
    108. 108. running the tests Copyright (C) 2011 Diego Torres Milano All rights reserved
    109. 109. running the tests what? Copyright (C) 2011 Diego Torres Milano All rights reserved
    110. 110. celsius to fahrenheit Fahrenheit 150112.5 75 37.5 0-37.5 -75 -40 -30 -20 -10 0 10 20 30 40 Celsius Copyright (C) 2011 Diego Torres Milano All rights reserved
    111. 111. celsius to fahrenheit Fahrenheit 150112.5 75 f = 9/5 * c + 32 37.5 0 c = (f-32) * 5/9-37.5 -75 -40 -30 -20 -10 0 10 20 30 40 Celsius Copyright (C) 2011 Diego Torres Milano All rights reserved
    112. 112. converterpublic class TemperatureConverter {! public static double fahrenheitToCelsius(double f) { / TODO Auto-generated method stub /! ! return 0;! }} Copyright (C) 2011 Diego Torres Milano All rights reserved
    113. 113. TemperatureConv erterTests Test case as base class create method stubs TemperatureConverter as CUT Copyright (C) 2011 Diego Torres Milano All rights reserved
    114. 114. method stubsselect the methods you want stubs created for Copyright (C) 2011 Diego Torres Milano All rights reserved
    115. 115. conversion testpublic void testFahrenheitToCelsius() {! ! for (double c: sConversionTableDouble.keySet()) {! ! ! final double f = sConversionTableDouble.get(c);! ! ! final double ca = TemperatureConverter.fahrenheitToCelsius(f);! ! ! final double delta = Math.abs(ca - c);! ! ! assertTrue(delta < 0.005);! ! }! } Copyright (C) 2011 Diego Torres Milano All rights reserved
    116. 116. conversion tableprivate static final HashMap<Double, Double> sConversionTableDouble =! ! ! new HashMap<Double, Double>();!static {! ! sConversionTableDouble.put(0.0, 32.0);! ! sConversionTableDouble.put(100.0, 212.0);! ! sConversionTableDouble.put(-1.0, 30.20);! ! sConversionTableDouble.put(-100.0, -148.0);! ! sConversionTableDouble.put(32.0, 89.60);! ! sConversionTableDouble.put(-40.0, -40.0);! ! sConversionTableDouble.put(-273.0, -459.40);} Copyright (C) 2011 Diego Torres Milano All rights reserved
    117. 117. run the testsCopyright (C) 2011 Diego Torres Milano All rights reserved
    118. 118. run the tests this assertion failsCopyright (C) 2011 Diego Torres Milano All rights reserved
    119. 119. creating test caseuse AndroidTestCase as base class use EditNumber as CUT Copyright (C) 2011 Diego Torres Milano All rights reserved
    120. 120. method stubsselect the Context constructor select other methods Copyright (C) 2011 Diego Torres Milano All rights reserved
    121. 121. testpublic final void testClear() {! ! final String value = "123.45";! ! mEditNumber.setText(value);! ! mEditNumber.clear();! ! final String expected = "";! ! final String actual = mEditNumber.getText().toString();! ! assertEquals(expected, actual);} Copyright (C) 2011 Diego Torres Milano All rights reserved
    122. 122. implementationpublic class EditNumber extends EditText { / ... /! public void clear() {! ! setText("");! }} Copyright (C) 2011 Diego Torres Milano All rights reserved
    123. 123. testpublic final void testSetNumber() {! ! final double d = 123.45;! ! mEditNumber.setNumber(d);! ! final String expected = Double.toString(d);! ! final String actual = mEditNumber.getText().toString();! ! assertEquals(expected, actual);} Copyright (C) 2011 Diego Torres Milano All rights reserved
    124. 124. testpublic final void testGetNumber() {! ! final double expected = 123.45;! ! mEditNumber.setNumber(expected);! ! final double actual = mEditNumber.getNumber();! ! assertEquals(expected, actual);} Copyright (C) 2011 Diego Torres Milano All rights reserved
    125. 125. implementationpublic class EditNumber extends EditText { / ... /! public void getNumber() { final String s = getText().toString(); if ( "".equals(s) ) { return Double.NaN; }! ! return Double.valueOf(s);! }} Copyright (C) 2011 Diego Torres Milano All rights reserved
    126. 126. run the tests NO videoCopyright (C) 2011 Diego Torres Milano All rights reserved
    127. 127. what’s the problem ? Copyright (C) 2011 Diego Torres Milano All rights reserved
    128. 128. what’s the problem ?clear() worksrequestFocus() workssetNumber() worksfahrenheitToCelsius() worksgetNumber() worksso ? Copyright (C) 2011 Diego Torres Milano All rights reserved
    129. 129. temperature converter Title celsius 100 32fahrenheit keyboard Copyright (C) 2011 Diego Torres Milano All rights reserved
    130. 130. temperature converter Title celsius 100 autoupdate 32fahrenheit keyboard Copyright (C) 2011 Diego Torres Milano All rights reserved
    131. 131. TemperatureChan geWatcher create it as an inner class implements TextWatcher inherited abstract methods create 2 fields mSource & mDest Copyright (C) 2011 Diego Torres Milano All rights reserved
    132. 132. generateconstructor use the fieldsomit call to super() Copyright (C) 2011 Diego Torres Milano All rights reserved
    133. 133. the watcherpublic abstract class TemperatureChangeWatcher implements TextWatcher {! ! private EditNumber mSource;! ! private EditNumber mDest;! !! ! public TemperatureChangeWatcher( EditNumber source, EditNumber dest) {! ! ! this.mSource = source;! ! ! this.mDest = dest;! ! } / ... /} Copyright (C) 2011 Diego Torres Milano All rights reserved
    134. 134. on text changed@Overridepublic void onTextChanged(CharSequence s, int start, int before, int count) {! if ( !mDest.hasWindowFocus() || mDest.hasFocus() || s == null ) return;! final String str = s.toString();! if ( "".equals(str) ) {! ! mDest.setText(""); return;! }! try {! ! final double result = convert(Double.parseDouble(str));! ! mDest.setNumber(result);! }! catch (NumberFormatException e) {! ! / WARNING: this is thrown while a number is entered, for example just a - /! }! catch (Exception e) {! ! mSource.setError("ERROR: " + e.getLocalizedMessage());! }} Copyright (C) 2011 Diego Torres Milano All rights reserved
    135. 135. on text changed@Overridepublic void onTextChanged(CharSequence s, int start, int before, int count) {! if ( !mDest.hasWindowFocus() || mDest.hasFocus() || s == null ) return;! final String str = s.toString();! if ( "".equals(str) ) {! ! mDest.setText(""); return; we should! } define it! try {! ! final double result = convert(Double.parseDouble(str));! ! mDest.setNumber(result);! }! catch (NumberFormatException e) {! ! / WARNING: this is thrown while a number is entered, for example just a - /! }! catch (Exception e) {! ! mSource.setError("ERROR: " + e.getLocalizedMessage());! }} Copyright (C) 2011 Diego Torres Milano All rights reserved
    136. 136. abstract convert methodpublic abstract class TemperatureChangeWatcher implements TextWatcher { //... protected abstract double convert(double temp); //...} Copyright (C) 2011 Diego Torres Milano All rights reserved
    137. 137. find views@Overridepublic void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); mCelsius = (EditNumber) findViewById(R.id.celsius); mFahrenheit = (EditNumber) findViewById(R.id.fahrenheit);} Copyright (C) 2011 Diego Torres Milano All rights reserved
    138. 138. add change listeners@Overridepublic void onCreate(Bundle savedInstanceState) { / ... / mCelsius.addTextChangedListener( we should new TemperatureChangeWatcher(mCelsius, mFahrenheit) { create it! ! ! @Override protected double convert(double temp) {! ! ! ! return TemperatureConverter.celsiusToFahrenheit(temp);! ! ! }! }); mFahrenheit.addTextChangedListener( new TemperatureChangeWatcher(mFahrenheit, mCelsius) {! ! ! @Override protected double convert(double temp) {! ! ! ! return TemperatureConverter.fahrenheitToCelsius(temp);! ! ! } }); } Copyright (C) 2011 Diego Torres Milano All rights reserved
    139. 139. add conversionpublic class TemperatureConverter {! public static double fahrenheitToCelsius(double f) {! ! return (f-32) * 5/9.0;! }! public static double celsiusToFahrenheit(double c) {! ! / TODO Auto-generated method stub /! ! return 0;! }} Copyright (C) 2011 Diego Torres Milano All rights reserved
    140. 140. adding testpublic class TemperatureConverterTests extends TestCase { / ... /! /**! * Test method for {@link TemperatureConverter#fahrenheitToCelsius(double)}.! */! public void testCelsiusToFahrenheit() {! ! for (double c: sConversionTableDouble.keySet()) {! ! ! final double f = sConversionTableDouble.get(c);! ! ! final double fa = TemperatureConverter.celsiusToFahrenheit(c);! ! ! final double delta = Math.abs(fa - f);! ! ! assertTrue("delta=" + delta + " for f=" + f + " fa=" + fa, delta < 0.005);! ! }! }} Copyright (C) 2011 Diego Torres Milano All rights reserved
    141. 141. running the tests Copyright (C) 2011 Diego Torres Milano All rights reserved
    142. 142. implementing conversionpublic class TemperatureConverter {! public static double fahrenheitToCelsius(double f) {! ! return (f-32) * 5/9.0;! }! public static double celsiusToFahrenheit(double c) {! ! return 9/5.0 * c + 32;! }} Copyright (C) 2011 Diego Torres Milano All rights reserved
    143. 143. running the tests Copyright (C) 2011 Diego Torres Milano All rights reserved
    144. 144. code coverageCopyright (C) 2011 Diego Torres Milano All rights reserved
    145. 145. code coverageCopyright (C) 2011 Diego Torres Milano All rights reserved
    146. 146. code coveragemeasures the amount of source code tested Copyright (C) 2011 Diego Torres Milano All rights reserved
    147. 147. code coveragemeasures the amount of source code testedandroid relies on emma (http://emma.sf.net) Copyright (C) 2011 Diego Torres Milano All rights reserved
    148. 148. code coveragemeasures the amount of source code testedandroid relies on emma (http://emma.sf.net)supported coverage types: class method line block Copyright (C) 2011 Diego Torres Milano All rights reserved
    149. 149. coverage reportCopyright (C) 2011 Diego Torres Milano All rights reserved
    150. 150. coverage reportoverall coverage summary Copyright (C) 2011 Diego Torres Milano All rights reserved
    151. 151. coverage reportoverall coverage summaryoverall stats summary Copyright (C) 2011 Diego Torres Milano All rights reserved
    152. 152. coverage reportoverall coverage summaryoverall stats summarycoverage breakdown by package Copyright (C) 2011 Diego Torres Milano All rights reserved
    153. 153. building with antdisable project’s Build Automatically in Eclipseconvert project to ant$ android update project --path $PWD --nameTemperatureConverter --target android-10$ android update test-project --main ../TemperatureConverter --path $PWD Copyright (C) 2011 Diego Torres Milano All rights reserved
    154. 154. run configuration coveragerun build.xml as Ant build... use coverage target Copyright (C) 2011 Diego Torres Milano All rights reserved
    155. 155. ant 1.8specify ant 1.8 home Ant home... Copyright (C) 2011 Diego Torres Milano All rights reserved
    156. 156. coveragerun build.xml coveragecoverage analysis report is generatedget coverage file$ adb pull /data/data/com.example.i2at.tc/files/coverage.ec coverage.ec Copyright (C) 2011 Diego Torres Milano All rights reserved
    157. 157. coverage reportCopyright (C) 2011 Diego Torres Milano All rights reserved
    158. 158. coverage reportCopyright (C) 2011 Diego Torres Milano All rights reserved
    159. 159. importing coverage fileimport the coverage session into Eclipse Copyright (C) 2011 Diego Torres Milano All rights reserved
    160. 160. coverage sessionselect the project folders Copyright (C) 2011 Diego Torres Milano All rights reserved
    161. 161. convert not covered Copyright (C) 2011 Diego Torres Milano All rights reserved
    162. 162. adding missing test@UiThreadTestpublic void testCelsiusToFahrenheitConversion() { ! mCelsius.clear();! ! mFahrenheit.clear();! ! final double c = 32.5;! ! mCelsius.requestFocus();! ! mCelsius.setNumber(c);! ! mCelsius.requestFocus();! ! final double expected = TemperatureConverter.celsiusToFahrenheit(c);! ! final double actual = mFahrenheit.getNumber();! ! final double delta = Math.abs(expected - actual);! ! assertTrue("delta=" + delta, delta < 0.005);} Copyright (C) 2011 Diego Torres Milano All rights reserved
    163. 163. coverageCopyright (C) 2011 Diego Torres Milano All rights reserved
    164. 164. constructor not covered Copyright (C) 2011 Diego Torres Milano All rights reserved
    165. 165. private constructorpublic class TemperatureConverter {! private TemperatureConverter() {! ! / do nothing /! }! public static double fahrenheitToCelsius(double f) {! ! return (f-32) * 5/9.0;! }! public static double celsiusToFahrenheit(double c) {! ! return 9/5.0 * c + 32;! }} Copyright (C) 2011 Diego Torres Milano All rights reserved
    166. 166. access private constructorpublic final void testPrivateConstructor() throws SecurityException, NoSuchMethodException,! ! ! IllegalArgumentException, InstantiationException, IllegalAccessException, InvocationTargetException {! Constructor<TemperatureConverter> ctor =! ! ! TemperatureConverter.class.getDeclaredConstructor();! ctor.setAccessible(true);! TemperatureConverter tc = ctor.newInstance((Object[])null);! assertNotNull(tc);} Copyright (C) 2011 Diego Torres Milano All rights reserved
    167. 167. access private constructorpublic final void testPrivateConstructor() throws SecurityException, NoSuchMethodException,! ! ! IllegalArgumentException, InstantiationException, IllegalAccessException, InvocationTargetException {! Constructor<TemperatureConverter> ctor = circumvent! ! ! TemperatureConverter.class.getDeclaredConstructor(); restriction! ctor.setAccessible(true);! TemperatureConverter tc = ctor.newInstance((Object[])null);! assertNotNull(tc);} Copyright (C) 2011 Diego Torres Milano All rights reserved
    168. 168. coverage reportCopyright (C) 2011 Diego Torres Milano All rights reserved
    169. 169. finished applicationthis is the final result Copyright (C) 2011 Diego Torres Milano All rights reserved
    170. 170. requirements converts between temperature units one temperature is entered and the other is updated error is displayed in the field right aligned, 2 decimal digits entry fields start emptyCopyright (C) 2011 Diego Torres Milano All rights reserved
    171. 171. continuous integration Copyright (C) 2011 Diego Torres Milano All rights reserved
    172. 172. continuous integrationagile technique for software engineeringreceived broad adoption in recent yearsprevents “integration hell”integrate changes frequently Copyright (C) 2011 Diego Torres Milano All rights reserved
    173. 173. requirementsversion control systemautomated buildself testedartifacts and tests results easy to find Copyright (C) 2011 Diego Torres Milano All rights reserved
    174. 174. installationdownload war from http://hudson-ci.org$ java -jar hudson.war Copyright (C) 2011 Diego Torres Milano All rights reserved
    175. 175. hudson homeCopyright (C) 2011 Diego Torres Milano All rights reserved
    176. 176. android pluginCopyright (C) 2011 Diego Torres Milano All rights reserved
    177. 177. android sdk rootCopyright (C) 2011 Diego Torres Milano All rights reserved
    178. 178. new jobCopyright (C) 2011 Diego Torres Milano All rights reserved
    179. 179. ant propertiesCopyright (C) 2011 Diego Torres Milano All rights reserved
    180. 180. build artifactsCopyright (C) 2011 Diego Torres Milano All rights reserved
    181. 181. build dependency these are the TemperatureConverterTest project options. This depends on TemperatureConverter. Copyright (C) 2011 Diego Torres Milano All rights reserved
    182. 182. android emulatorCopyright (C) 2011 Diego Torres Milano All rights reserved
    183. 183. android emulatorCopyright (C) 2011 Diego Torres Milano All rights reserved
    184. 184. build with antCopyright (C) 2011 Diego Torres Milano All rights reserved
    185. 185. xml test resultsdownload xmlinstrumentationtestrunner.jarreplace instrumentation byandroid:name="com.neenbedankt.android.test.XMLInstrumentationTestRunner"customize build.xml Copyright (C) 2011 Diego Torres Milano All rights reserved
    186. 186. junit test resultCopyright (C) 2011 Diego Torres Milano All rights reserved
    187. 187. test reportCopyright (C) 2011 Diego Torres Milano All rights reserved
    188. 188. behavior driven developmentCopyright (C) 2011 Diego Torres Milano All rights reserved
    189. 189. behavior driven developmentevolution of Test Driven Developmentinclusion of business participantcommon vocabularybased on Neuro Linguistics Programming Copyright (C) 2011 Diego Torres Milano All rights reserved
    190. 190. fitnesseCopyright (C) 2011 Diego Torres Milano All rights reserved
    191. 191. test suiteCopyright (C) 2011 Diego Torres Milano All rights reserved
    192. 192. slim test fixturepackage com.example.i2at.tc.test.fitnesse.fixture;import com.example.i2at.tc.TemperatureConverter;public class TemperatureConverterCelsiusToFahrenheitFixture {! private double celsius;! public void setCelsius(double celsius) {! ! this.celsius = celsius;! }! public String fahrenheit() throws Exception {! ! try {! ! ! return String.valueOf(TemperatureConverter.celsiusToFahrenheit(celsius));! ! } catch (RuntimeException e) {! ! ! return e.getLocalizedMessage();! ! }! }} Copyright (C) 2011 Diego Torres Milano All rights reserved
    193. 193. test runCopyright (C) 2011 Diego Torres Milano All rights reserved
    194. 194. questions ?Copyright (C) 2011 Diego Torres Milano All rights reserved
    195. 195. android application testing guide Copyright (C) 2011 Diego Torres Milano All rights reserved
    196. 196. android application testing guide Apply testing techniques and tools• Learn the nuances of Unit and Functional testing• Understand different development methodologies such as TDD and BDD• Apply Continuous Integration• Improve applications using performance tests• Expose your application to a wide range of conditions Copyright (C) 2011 Diego Torres Milano All rights reserved
    197. 197. thank youCopyright (C) 2011 Diego Torres Milano All rights reserved
    1. ¿Le ha llamado la atención una diapositiva en particular?

      Recortar diapositivas es una manera útil de recopilar información importante para consultarla más tarde.

    ×