SlideShare ist ein Scribd-Unternehmen logo
1 von 38
Testseverywhere
From unit testing to UI testing for Android
★ @laura_morillo
★ SoftwareDeveloper atCabify
★ Tech&LadiesandAgileGirlsorganizer
wheredoIstart?
https://io2015codelabs.appspot.com/
Androidtests
UNITTESTS
(runontheJVM)
instrumentationtests
(Runondeviceoremulator)
CONFIGURINGUNITTESTS
1. 2.
3.
Classtotest
TESTWIZARD
TestCalculator.java
TestCalculator.java
FirstTestImplementation
JUnittraditionalassertmethods
JUnitbetterassertmethod(withhamcrest!)
ExecutingUnitTests
or
Checkingtestresults(AndroidStudio)
Checkingtestresults(Console)
Implementingthecode
(That was easy!)
Anddone!
Configuringinstrumentation tests(I)
Configuringinstrumentation tests(II)
Configuringinstrumentation tests(III)
UITotest
ActivityTest
Espressotest
Espressotest:Step1
Espressotest:Step2
Espressotest:Step3
Espressoispowerful
We can interact with views (onView)
We can interact with data adapters
(onData)
Go back (pressBack)
Open menus
(openActionBarOverflowOrOptionsMenu and
openContextualActionModeOverflowMenu)
And check if the element is checked
(isChecked), can be clicked
(isClickable), is being displayed in the
screen (isDisplayed)...
Image courtesy of jesadaphorn at FreeDigitalPhotos.net
UITestingisnice…buttooslow
Solet’sdomoreJVMunit/Small test
Andwemocktheandroiddependencies
Butmockingisnotalwaysnice
Parcellable example
Servicesalsoneedandroidwithoutui
Servicesrule!
Butnotallservicesrule!
IntentService
EspressoIntentstestRule: Stubbing
EspressoIntentstestRule: Verification
Summary
We have Unit tests (JVM) and Instrumentation Tests (Android
Device)
Add Unit test as much as possible.
Add mocks for your dependencies when needed.
ActivityTestRule to test activities controlling their
lifecycle.
ServiceTestRule to test Services controlling their
lifecycle (but not valid for IntentService)
Espresso IntentsTestRule to handle activities and stub and
verify intents
Thankyou!
Laura Morillo-Velarde
@laura_morillo
laura.morillovelarde@gmail.com

Weitere ähnliche Inhalte

Andere mochten auch

AndrewLeeming_COSENERS-2014
AndrewLeeming_COSENERS-2014AndrewLeeming_COSENERS-2014
AndrewLeeming_COSENERS-2014
Andrew Leeming
 
Complete list of publications december 2015 Sten Rasmussen
Complete list of publications december 2015 Sten RasmussenComplete list of publications december 2015 Sten Rasmussen
Complete list of publications december 2015 Sten Rasmussen
Sten Rasmussen
 

Andere mochten auch (19)

Where's wilma
Where's wilma Where's wilma
Where's wilma
 
PROYECTO 8
PROYECTO 8PROYECTO 8
PROYECTO 8
 
Disiillusionment english poem by faiz ahmed faiz
Disiillusionment english poem by faiz ahmed faizDisiillusionment english poem by faiz ahmed faiz
Disiillusionment english poem by faiz ahmed faiz
 
AndrewLeeming_COSENERS-2014
AndrewLeeming_COSENERS-2014AndrewLeeming_COSENERS-2014
AndrewLeeming_COSENERS-2014
 
Pitches ThingsCon Amsterdam 2015
Pitches ThingsCon Amsterdam 2015Pitches ThingsCon Amsterdam 2015
Pitches ThingsCon Amsterdam 2015
 
coseners-2013
coseners-2013coseners-2013
coseners-2013
 
Grupo n 5
Grupo n 5Grupo n 5
Grupo n 5
 
المهارات اللازمة لطلاب كلية التربية للتعامل مع ذوي الاحتياجات الخاصة
  المهارات اللازمة لطلاب كلية التربية للتعامل مع ذوي الاحتياجات الخاصة  المهارات اللازمة لطلاب كلية التربية للتعامل مع ذوي الاحتياجات الخاصة
المهارات اللازمة لطلاب كلية التربية للتعامل مع ذوي الاحتياجات الخاصة
 
Dayana quezada
Dayana quezadaDayana quezada
Dayana quezada
 
Grupo 8
Grupo 8Grupo 8
Grupo 8
 
Eumind action plan PPS BHANDUP- YOUTH
Eumind action plan PPS BHANDUP- YOUTHEumind action plan PPS BHANDUP- YOUTH
Eumind action plan PPS BHANDUP- YOUTH
 
Complete list of publications december 2015 Sten Rasmussen
Complete list of publications december 2015 Sten RasmussenComplete list of publications december 2015 Sten Rasmussen
Complete list of publications december 2015 Sten Rasmussen
 
с.м. телегин52015
с.м. телегин52015с.м. телегин52015
с.м. телегин52015
 
Entry mode nyp
Entry mode nypEntry mode nyp
Entry mode nyp
 
Don't Risk it All: Ten Tips for Maximizing Business Value
 Don't Risk it All: Ten Tips for Maximizing Business Value Don't Risk it All: Ten Tips for Maximizing Business Value
Don't Risk it All: Ten Tips for Maximizing Business Value
 
Martti Ahtisaari
Martti AhtisaariMartti Ahtisaari
Martti Ahtisaari
 
EXPOSICIÓN nº 6
EXPOSICIÓN nº 6EXPOSICIÓN nº 6
EXPOSICIÓN nº 6
 
6 tips for a beautiful smile
6 tips for a beautiful smile6 tips for a beautiful smile
6 tips for a beautiful smile
 
Gtupo 3
Gtupo 3Gtupo 3
Gtupo 3
 

Ähnlich wie Tests everywhere

2012 java one-con3648
2012 java one-con36482012 java one-con3648
2012 java one-con3648
Eing Ong
 
2012 mobile testingsummit-moet
2012 mobile testingsummit-moet2012 mobile testingsummit-moet
2012 mobile testingsummit-moet
Eing Ong
 
2011 py con
2011 py con2011 py con
2011 py con
Eing Ong
 
MOET: Mobile End-to-End Testing
MOET: Mobile End-to-End TestingMOET: Mobile End-to-End Testing
MOET: Mobile End-to-End Testing
mobiletestsummit
 

Ähnlich wie Tests everywhere (20)

Mobile testing in the cloud
Mobile testing in the cloudMobile testing in the cloud
Mobile testing in the cloud
 
WindowTester PRO
WindowTester PROWindowTester PRO
WindowTester PRO
 
Automated UI Testing for Web and Native Apps on iOS and Android
Automated UI Testing for  Web and Native Apps on iOS and AndroidAutomated UI Testing for  Web and Native Apps on iOS and Android
Automated UI Testing for Web and Native Apps on iOS and Android
 
Android testing part i
Android testing part iAndroid testing part i
Android testing part i
 
2012 java one-con3648
2012 java one-con36482012 java one-con3648
2012 java one-con3648
 
Unit Testing in Android
Unit Testing in AndroidUnit Testing in Android
Unit Testing in Android
 
Android testing
Android testingAndroid testing
Android testing
 
Android automation tools
Android automation toolsAndroid automation tools
Android automation tools
 
Pragmatic UI testing with Compose Semantics.pdf
Pragmatic UI testing with Compose Semantics.pdfPragmatic UI testing with Compose Semantics.pdf
Pragmatic UI testing with Compose Semantics.pdf
 
2012 mobile testingsummit-moet
2012 mobile testingsummit-moet2012 mobile testingsummit-moet
2012 mobile testingsummit-moet
 
2011 py con
2011 py con2011 py con
2011 py con
 
Android UI Testing with uiautomator
Android UI Testing with uiautomatorAndroid UI Testing with uiautomator
Android UI Testing with uiautomator
 
Overview the Challenges and Limitations of Android App Automation with Espres...
Overview the Challenges and Limitations of Android App Automation with Espres...Overview the Challenges and Limitations of Android App Automation with Espres...
Overview the Challenges and Limitations of Android App Automation with Espres...
 
MOET: Mobile End-to-End Testing
MOET: Mobile End-to-End TestingMOET: Mobile End-to-End Testing
MOET: Mobile End-to-End Testing
 
Espresso
EspressoEspresso
Espresso
 
Deviceanywhere studio 5.1
Deviceanywhere studio 5.1Deviceanywhere studio 5.1
Deviceanywhere studio 5.1
 
Unit Testing in Angular
Unit Testing in AngularUnit Testing in Angular
Unit Testing in Angular
 
Using Robots for App Testing
Using Robots for App Testing Using Robots for App Testing
Using Robots for App Testing
 
Android Building, Testing and reversing
Android Building, Testing and reversingAndroid Building, Testing and reversing
Android Building, Testing and reversing
 
Ui qa tools
Ui qa toolsUi qa tools
Ui qa tools
 

Kürzlich hochgeladen

Obat Penggugur Kandungan Di Apotik Kimia Farma (087776558899)
Obat Penggugur Kandungan Di Apotik Kimia Farma (087776558899)Obat Penggugur Kandungan Di Apotik Kimia Farma (087776558899)
Obat Penggugur Kandungan Di Apotik Kimia Farma (087776558899)
Cara Menggugurkan Kandungan 087776558899
 

Kürzlich hochgeladen (6)

Satara Call girl escort *74796//13122* Call me punam call girls 24*7hour avai...
Satara Call girl escort *74796//13122* Call me punam call girls 24*7hour avai...Satara Call girl escort *74796//13122* Call me punam call girls 24*7hour avai...
Satara Call girl escort *74796//13122* Call me punam call girls 24*7hour avai...
 
Mobile Application Development-Android and It’s Tools
Mobile Application Development-Android and It’s ToolsMobile Application Development-Android and It’s Tools
Mobile Application Development-Android and It’s Tools
 
Leading Mobile App Development Companies in India (2).pdf
Leading Mobile App Development Companies in India (2).pdfLeading Mobile App Development Companies in India (2).pdf
Leading Mobile App Development Companies in India (2).pdf
 
Mobile Application Development-Components and Layouts
Mobile Application Development-Components and LayoutsMobile Application Development-Components and Layouts
Mobile Application Development-Components and Layouts
 
Android Application Components with Implementation & Examples
Android Application Components with Implementation & ExamplesAndroid Application Components with Implementation & Examples
Android Application Components with Implementation & Examples
 
Obat Penggugur Kandungan Di Apotik Kimia Farma (087776558899)
Obat Penggugur Kandungan Di Apotik Kimia Farma (087776558899)Obat Penggugur Kandungan Di Apotik Kimia Farma (087776558899)
Obat Penggugur Kandungan Di Apotik Kimia Farma (087776558899)
 

Tests everywhere

Hinweis der Redaktion

  1. Cuando empiezas a trabajar de nuevas en un tema puede ser difícil encontrar la documentación adecuada. Google ha intentado mejorar eso sacando una serie de Codelabs cada año con motivo de su conferencia anual Google I/O en los que permite tocar temas muy diversos como Android, web, polymer. Uno de los cursos que sacaron este año fue Unit and UI Testing in Android Studio y en él se basa parte del material que voy a ir explicando. Si alguien quiere ir probando las cosas por sí mismo, puesto que sin duda haciendo las cosas una misma es como más se aprende.
  2. En Android tenemos dos bloques grandes de tests que están muy diferenciados. Tenemos por un lado los tests unitarios, los cuales son simplemente típicos tess de Java que se ejecutan en la máquina virtual de java, con la característica de que gradle nos proporciona una implementación fake de las clases Android que por defecto lanza excepciones si invocas a métodos Android, ya que en este tipo de tests no deberíamos hacer uso de sus funciones. Por otro lado tenemos el bloque de los tests de instrumentación. Estos tests dependen completamente de Android y por lo tanto tienen que ejecutarse o bien en un dispositivo o bien en el emulador.
  3. Vamos a empezar viendo los tests unitarios. Para configurar el entorno de AndroidStudio para trabajar con los tests unitarios necesitamos hacer tres cosas: 1. Seleccionar en el selector de Test Artifact de la ventana de Build Variants la opción de Test Unit. 2. A continuación creamos el árbol de carpetas test/java bajo la carpeta src. Para hacer esto tendremos que estar en la vista de Project puesto que con la vista de Android no veríamos el árbol completo. 3. El último paso que tenemos que hacer es añadir la dependencia a la librería de testing. Mi recomendación es usar junit 4 y la última versión estable que hay que es la 4.4. Para añadir la dependencias tenemos que añadir la llamada a testCompile con la librería dentro de las dependencias en nuestro fichero gradle.
  4. Ahora que ya tenemos el proyecto configurado creamos una clase que será la que vamos a testear. En este ejemplo se trata de una calculadora. Para crear la clase de test podemos hacerlo manualmente o también desde la clase que queremos probar podemos acceder a la opción GoTo -> Test del menú contextual al pinchar sobre la clase.
  5. Esa llamada nos va a lanzar un wizard sencillo que nos va a ayudar a generar la clase. Nos da la opción de seleccionar la librería de testing, el paquete, si queremos añadir métodos de setup y teardown y nos permite seleccionar los métodos de la clase que queremos testear.
  6. Usando el wizard nos crearía una clase tal que así. Al haber seleccionado la opción de setUp generará el método setUp con la anotación Before donde podremos poner nuestro código de preparación para los tests y crea un método testSum para probar el método sum anotado con @Test. Pero ese nombre testSum no ayuda mucho
  7. Durante unos años Google llevó a cabo una iniciativa que no sé si continúa llamada Testing on the Toilet. En ella se dedicaban a escribir una serie de panfletos con buenas prácticas relacionadas con el testing, inyección de dependencias y similar y como querían conseguir que llegaran a todo el mundo decidieron que el mejor sitio para ponerlos era el baño. Como la iniciativa tuvo mucho éxito dicidieron publicar esas hojas también en internet incluso en una versión fácil de imprimir en pdf para que cualquiera pueda ponerlas en el baño de su oficina. Y el contenido de muchas de ellas es bastante bueno, como en esta que vemos aquí en la que precisamente trata sobre el naming. Podemos ver un ejemplo con un nombre de test que a pesar de ser mejor que testSum sigue sin dejar muy claro qué está testeando, sabemos que se testea el método isUserLockedOut para login inválido, pero para tener más detalles necesitamos entrar a leer el código. Sin embargo, si llamamos al test isUserLockedOut:lockOutUserAfterThreeInvalidLoginAttemps, aunque es largo queda claramente definido el objetivo de ese test.
  8. Por ello volviendo a nuestro ejemplo de la calculadora yo prefiero usar nombres del estilo de sum_returnsTheAdditionForTwoPositiveNumbers o quizás sum_throwsAnExceptionForNegativeNumbers si por ejemplo quisiéramos que una restricción de nuestro método es que solo suma números positivos.
  9. Ahora que ya tenemos el esqueleto del test, vamos a ver el contenido. En junit existen una gran variedad de métodos que nos permiten hacer comparaciones como assertTrue, assertFalse, assertEqual. En el ejemplo usamos assertEquals para dos dobles con una desviación. Sin embargo los métodos de junit a menudo pueden ser un poco confusos, es difícil recordar qué va primero lo esperado o lo calculado? Por ello existe una librería llamada hamcrest que permite que las comprobaciones sean más semánticas y más legibles. Por eso a partir de la versión 4.4 de junit han decidido añadir el método assertThat y han incluído también