Getting Started with Testing Test preconditions orde could vary.So it's custo mary to create a on(be t for prec s.Tho ere is n this tes any spe order,it is good practice to keep e precon ons toge the or organ a purpose The actual tests void metho will be onsidered as est opp d to JUni dis find th T ame ver able ndroid test fr ch a 11 they don't turn a simple method into a test.Instead they o ranize them in different categories.Ultimately you will have the ability to run tests for a single category using the test runner. As a rule of thumb,name your tests in a descriptive way using nouns and the condition being tested. For example:testvalues(),testConversionError(), testconversionTostring()are all valid test names. Test for exceptions and wrong values instead of just testing for positive cases. uring the execution of the test some conditions,side effects,or method returns should be compared against the e ctations To ease these c provides a full set of asermethods to compare the expected results from the test to the actual results after running with them throwing exceptions if conditions are not met.Then the test runner handles these exceptions and presents the results. These methods,which are overloaded to support different arguments,include 。a8 sertEgual8() assertFalse() assertNotNull() ·assertNotSame() assertNull() assertSame() ·assertTrue() ·fai10 161
Getting Started with Testing [ 16 ] Test preconditions Usually there is no way to test for preconditions as the tests are discovered using introspection and their order could vary. So it's customary to create a testPreconditions() method to test for preconditions. Though there is no assurance that this test will be called in any specific order, it is good practice to keep this and the preconditions together for organizational purposes. The actual tests All public void methods whose names start with test will be considered as a test. JUnit 3, as opposed to JUnit 4, doesn't use annotations to discover the tests but introspection to find their names. There are some annotations available on the Android test framework such as @SmallTest, @MediumTest, and @LargeTest, but they don't turn a simple method into a test. Instead they organize them in different categories. Ultimately you will have the ability to run tests for a single category using the test runner. As a rule of thumb, name your tests in a descriptive way using nouns and the condition being tested. For example: testValues(), testConversionError(), testConversionToString() are all valid test names. Test for exceptions and wrong values instead of just testing for positive cases. During the execution of the test some conditions, side effects, or method returns should be compared against the expectations. To ease these operations, JUnit provides a full set of assert* methods to compare the expected results from the test to the actual results after running with them throwing exceptions if conditions are not met. Then the test runner handles these exceptions and presents the results. These methods, which are overloaded to support different arguments, include: • assertEquals() • assertFalse() • assertNotNull() • assertNotSame() • assertNull() • assertSame() • assertTrue() • fail()
Chapter1 In addition to these JUnit assert methods,Android extends Assert in two specialized classes providing additional tests: ·MoreAsserts ·ViewAsserts Mock objects tion. Generally,this is do elp,as rethat t e your tests m the surrounding universe and en The Android testing framework supports objects that you will find when you will ned to provide ome ependenc by the Android n the MockApplication MockContentProvider MockContentResolver MockContext ·MockCursor MockDialogInterface MockPackageManager ·MockResources Almost any component of the platform that could interact with your Activity can be created by instantiating one of these classes. However,they are not real implementations but stubs where every method generates an UnsupportedoperationException and that you can extend to create real mock objects. 【171
Chapter 1 [ 17 ] In addition to these JUnit assert methods, Android extends Assert in two specialized classes providing additional tests: • MoreAsserts • ViewAsserts Mock objects Mock objects are mimic objects used instead of calling the real domain objects to enable testing units in isolation. Generally, this is done to ensure that correct methods are called but they can also be of help, as mentioned, to isolate your tests from the surrounding universe and enable you to run them independently and repeatably. The Android testing framework supports several mock objects that you will find very useful when writing your tests but you will need to provide some dependencies to be able to compile the tests. Several classes are provided by the Android testing framework in the android. test.mock package: • MockApplication • MockContentProvider • MockContentResolver • MockContext • MockCursor • MockDialogInterface • MockPackageManager • MockResources Almost any component of the platform that could interact with your Activity can be created by instantiating one of these classes. However, they are not real implementations but stubs where every method generates an UnsupportedOperationException and that you can extend to create real mock objects
Getting Started with Testing Ul tests Finally,special considera ave already nown only the main threa articular test should be run n that thread and would hav herhand youynt torn parts of your esn thed you may use the Activity.runonuiThread(Runnable r)method providing the corresponding Runnable containing testing instructions. A helper class Touchutis is also provided to aid in the UI test creation allowing the generation of events to send to the Views,such as: ·click ·drag ·long click ·scroll ·tap ·touch By these means you can actually remote control you application from the tests. Eclipse and other IDE support JUnit is fully supported by Eclipse and the Android ADT plugin lets you create Android testing projects.Furthermore,you can run the tests and analyze the results without leaving the IDE. This also provides a more subtle advantage;being able to run the tests from Eclipse allows you to debug the tests that are not behaving correctly. In the screenshot,we can see how Eclipse runs 18 tests taking 20.008 seconds,where 0 Errors and 0 Failures were detected.The name of each test and its duration is also displayed.If there was a failure,the Failure Trace would show the related information. 【18]
Getting Started with Testing [ 18 ] UI tests Finally, special consideration should be taken if your tests involve UI components. As you may have already known, only the main thread is allowed to alter the UI in Android. Thus a special annotation @UIThreadTest is used to indicate that a particular test should be run on that thread and would have the ability to alter the UI. On the other hand, if you only want to run parts of your test on the UI thread, you may use the Activity.runOnUiThread(Runnable r) method providing the corresponding Runnable containing testing instructions. A helper class TouchUtils is also provided to aid in the UI test creation allowing the generation of events to send to the Views, such as: • click • drag • long click • scroll • tap • touch By these means you can actually remote control you application from the tests. Eclipse and other IDE support JUnit is fully supported by Eclipse and the Android ADT plugin lets you create Android testing projects. Furthermore, you can run the tests and analyze the results without leaving the IDE. This also provides a more subtle advantage; being able to run the tests from Eclipse allows you to debug the tests that are not behaving correctly. In the screenshot, we can see how Eclipse runs 18 tests taking 20.008 seconds, where 0 Errors and 0 Failures were detected. The name of each test and its duration is also displayed. If there was a failure, the Failure Trace would show the related information
Chapter 1 Package Hierarch Junit8口日 Runs:18/18BErrors:0 Failures:0 com.exampleaatg temper testEahrenheitTocelsiusint (0 202 s com.example.aatg.temperatureconver bcom.example.aatg.temperatureconvert 三Failure Trace to some degree bi t they are not Even if you are not developing in an IDE,you can find suppor cp: apacn hthn the ts with s setup sing the s test-project a lescribed by this help text s android -help create test-proiect android [global options]create test-project [action options] Global options: -v-verbose Verbose mode:errors,warnings and informational messages are printed. -h -help Help on a specific command. -s-silent silent mode:only errors are printed out 【19]
Chapter 1 [ 19 ] Other IDEs like ItelliJ and Netbeans have plugins integrating Android development to some degree but they are not officially supported. Even if you are not developing in an IDE, you can find support to run the tests with ant (check http://ant.apache.org if you are not familiar with this tool). This setup is done by the android command using the subcommand create test-project as described by this help text: $ android -help create test-project Usage: android [global options] create test-project [action options] Global options: -v -verbose Verbose mode: errors, warnings and informational messages are printed. -h -help Help on a specific command. -s -silent Silent mode: only errors are printed out
Getting Started with Testing Action "create test-project": Creates a new Android project for a test package. Options: -p-path The new project's directory [required] direetorto directody of the app under teat,relative to the -n-name Project name Integration tests ndividual c ork ioi epe ed together to test the integration. Usually android activities red with the nfrastructur ovided by the ActivityManager and access to resources,filesystem,and databases. The same criteria apply to other Android components like services or Contentroiders that need to interact with other parts of the system to achieve their function. In all these cases there are specialized tests provided by the Android testing framework that facilitate the creation of tests for these components. Functional or acceptance tests In agile software development,functional or acceptance tests are usually created by business and Quality A surance (QA)people and expressed in a business domain language.These are gh lev tests to tes compl nes an orrec feature.Ihey tsOA.teste ugh c on be (produc)ar the of these te Some frameworksand o hep in this field,m st notably fitNesse w.fitr ra)which can he asily inte grated. to development process and will let you create ac eptance tests and check their results 【201
Getting Started with Testing [ 20 ] Action "create test-project": Creates a new Android project for a test package. Options: -p -path The new project's directory [required] -m -main Path to directory of the app under test, relative to the test project directory [required] -n -name Project name As indicated by the help you should provide at least the path to the project (-path) and the path to the main project or the project under test (-main). Integration tests 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. Usually 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. The same criteria apply to other Android components like Services or ContentProviders that need to interact with other parts of the system to achieve their function. In all these cases there are specialized tests provided by the Android testing framework that facilitate the creation of tests for these components. Functional or acceptance tests 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. They are created ideally through collaboration between business customers, business analysts, QA, testers, and developers. However the business customers (product owners) are the primary owners of these tests. Some frameworks and tools can help in this field, most notably FitNesse (http:// www.fitnesse.org), which can be easily integrated, up to a point, into the Android development process and will let you create acceptance tests and check their results