domingo, 5 de abril de 2015

Espresso and Android Studio


Required
To have installed Android Studio 1.0.1 or up.

Installing Espresso in Android Studio

1. Over your project created open the build.gradle file and add

To dependencies:
// Apps dependencies, including test
compile 'com.android.support:support-annotations:21.0.3'
// Testing-only dependencies
androidTestCompile 'com.android.support.test:testing-support-lib:0.1'
androidTestCompile 'com.android.support.test.espresso:espresso-core:2.0'

To defaultConfig:
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"

To packagingOpptions:
exclude'LICENSE.txt'
Fig 1. Example build.gradle file.

2. Create the Class test having in mind the next features
The class extend that ActivityInstrumentationTestCase2 class.
The package that contain these classes test is the package defined in AndroidManifiest.xml.
The class uses the static references i.e. import static android.support.test.espresso.Espresso.onView.

Fig 2. Example Test file.

In this case I have defined one operation test that validate to show the text "Hello World!" on the view of the activity. That is a simple test, remember that you can visit Espresso site to define sophisticated  test.

3. To define and setting up of the Test case
Sets up your test using "Edit configuration".
In Android test add the new test case (+).
Define the name for example Espresso test.
Define the class test that in this case is FunctionalInstrumentationTest.
Specific the instrumentation runner like as AndroidJUnitRunner.


Fig 3. Example setting up the test case.

I recommend  enable "Show chooser dialog" and always to use a device real. To be honest, I prefer always work with a device real and don't use the emulator.

4. Running the Test case created.
Choose your test case crated and click over Run option, then choose your device connected and automatically the test is going to run.

Fig 4. Example running the test case.

Finally, you will see the results and also export it using Android Studio options. You can also checking the logs from the test case.

Fig 5. Export the results form your test case.

And that's it. If you have any question, please let me know. You can download the example project in GitHub.
Good travel.

JUnit and Android Studio


Required
To have installed Android Studio 1.0.1 or up.

Installing JUnit in Android Studio

1. Over your project created open the build.gradle file and add

To dependencies:
// Apps dependencies, including test
compile 'com.android.support:support-annotations:21.0.3'
// Testing-only dependencies
androidTestCompile 'com.android.support.test:testing-support-lib:0.1'
androidTestCompile 'com.android.support.test.espresso:espresso-core:2.0'

To defaultConfig:
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"

To packagingOpptions:
exclude'LICENSE.txt'
Fig 1. Example build.gradle file.

2. A little about JUnit for Android
In the framework JUnit for Android you can make test cases with the next classes:

ApplicationTestCase: Verifies the Application classes in a controlled environment.
AndroidTestCase: It contains methods for accessing resources like Activity Context.
IntrumentationTestCase: Verifies a particular feature or behavior of target application, e.g. verify UI output of application.

And a set of classes for component-specified test case like:

Activity Testing
ActivityTestCase class, used to test UI interaction like key event, touch event.

Content Provider Testing
ProviderTestCase class, used to test store and retrieve data and make it accessible across applications.

Service Testing
ServiceTestCase class, used to test various states of Services life cycle and interaction between application and service.

3. Mocks Object Classes
Additionally, Android provides classes that create mock system objects like:
Context Object, ContentProvider Object, ContentResolver Object, Service Object, Intent Object. These mocks facilitate dependency injection for testing.

4. Let's do it!
We are going to do two test case very useful, GPSTest and ConnectivityTest. Both classes extend from AndroidTestCase class, this kind of testing it provides methods for testing permissions.

GpsLocationTest uses the LocationManager class and verifies that the GPS is available and the app had the permissions.

Fig 2. GpsLocationTest  class.

ConnectivityTest uses the ConnectivityManager class to verified the accesses to network and the HTTP connectivity.

Fig 3. ConnectivityTest  class.

You have also an example that ApplicationTest:

Fig 4. ApplicationTest class.

4. Setting up and Running the Test case created.
Choose your test case crated and click over Run option, then choose your device connected and automatically the test is going to run. Please, to see for more detail the article Espresso con Android Studio.

You can download the example project in GitHub.
Good travel.

Testing Android Applications

Introducción


Como es bien conocido dentro del proceso de desarrollo de una solución móvil es necesario realizar los respectivos guiones de pruebas y pruebas unitarias al software para garantizar la entrega de un producto con un nivel de calidad aceptable y garantizar el mínimo de errores posibles en nuestro servicio.

A diferencia del software convencional las pruebas de una solución móvil no se enfocan netamente al testeo técnico de los componentes (Wifi disponible, GPS activo, Conexión http disponible), hay que considerar con la misma importancia al testeo funcional de los componentes (Interacción con las pantallas, Navegación entre Activities, Contenidos de la vista disponible). Por ello cuando hablamos de testear una App hablamos de dos niveles de pruebas:

- Functional testing
- Technical testing

Para ello contamos con diferentes frameworks en el mercado que podemos integrar al entorno de desarrollo. Esto quiere decir que usualmente no se utiliza una sóla herramienta para testear el App si no que es necesario usar múltiples herramientas dependiendo del nivel de testing que se requiera ejecutar.

Nota: Creo que la razón por la que no hay una única herramienta de testing de App Android ha sido básicamente a que se han desarrollado como proyectos de testing independientes. Actualmente Google ha hecho el esfuerzo de integrar algunas en Android Studio. Tal es el caso de Espresso y JUnit.

Functional testing
Estas pruebas unitarias estresan el App a nivel de funcionalidad y valida los componentes visuales de la aplicación, operaciones como

- Visibilidad de botones, textos, imágenes, checkbox, frames, etc.
- Eventos de clics sobre textos, imágenes, checkbox, etc.
- Valores por defecto de listas de selección
- Número mínimo o máximo de listas de selección.
- Atributos de componentes visuales tales como ancho y altura.

Para realizar estas pruebas podemos usar EspressoRobolectricRobotium, o Calabash.
En el artículo Espresso in Android Studio se detalla como trabajar Espresso con Android Studio.

Technical testing
Estas pruebas unitarias son enfocadas en probar los operaciones técnicas y de negocio que debe realizar el App, entre las más comunes son:

- Acesso a la red (http conection).
- GPS activo
- Wifi encendido
- Acceso a contactos
- Permisos de escritura sobre la memoria externa (SDCard)
- Finalización de procesos asyncronos, etc.

Para realizar estos test podemos usar Junit o Hamcrest.
En el artículo JUnit in Android Studio se detalla como trabajar JUnit con Android Studio.

Conclusión
Depende de la complejidad del proyecto y del software los niveles de testing que definirás. El promedio de aplicaciones sólo requeriran pruebas con JUnit/Espresso pero finalmente el factor que decide que framework usar será los guiones de pruebas que necesite abarcar el testing. Sin embargo mi recomendación es seguir las pautas marcadas por Google y siempre incluir al menos las pruebas unitarias dentro del proceso de desarrollo como una buena práctica.