SlideShare uma empresa Scribd logo
1 de 16
Baixar para ler offline
Unit and
Automation
Testing
on Android
Stanislav Gatsev
Android Team Lead,
Melon Inc.
Who am I?
Stanislav Gatsev
Android Team Lead
+359 89 891 4481
stanislav.gatsev@melontech.com
http://www.melon.bg
What is Android?
o World's most popular mobile
platform
o Every day another million users
power up their Android devices for
the first time
o Using Android SDK we can develop
software for almost everything from
smartphones and tablets to
glasses, watches, TVs and even
cars.
Why we automate testing?
o We save time !!!
o We improve our code quality
o We support live documentation
o We run our regression tests
o We fight fragmentation
Our Example Project
What Can We Test?
o We can test our logic, algorithms, calculations
o We can test our UI and navigation logic
o We can test IO operations, database and network
operations
o And more...
@SmallTest
public void test_addOperatorInJava() throws Exception {
Assert.assertEquals(4, 2 + 2);
Assert.assertEquals(27, 25 + 2);
}
@SmallTest
public void test_FieldsAreVisible() {
ViewAsserts.assertOnScreen(mRootView, mEmailEditText);
ViewAsserts.assertOnScreen(mRootView, mPasswordEditText);
ViewAsserts.assertOnScreen(mRootView, mLoginActionLayout);
}
How we automate testing?
o We use JUnit
o We mock our objects
o We are using activity testing framework
o We click with Robotium
JUnit and Android
We can use the JUnit TestCase class to do unit testing on a class that
doesn't call Android APIs. TestCase is also the base class for
AndroidTestCase, which we can use to test Android-dependent objects.
Besides providing the JUnit framework, AndroidTestCase offers
Android-specific setup, teardown, and helper methods.
public class UtilTests extends AndroidTestCase {
@SmallTest
public void test_StringToLatLngValidValues() throws Exception {
String latLngString = "34.009555,-118.497072";
LatLng latLng = Util.stringToLatLng(latLngString);
Assert.assertEquals(Double.compare(latLng.latitude, 34.009555), 0);
Assert.assertEquals(Double.compare(latLng.longitude, -118.497072), 0);
}
@SmallTest
public void test_StringToLatLngValidInvalues() throws Exception {
String latLngString = "34.009555,-a118.497072";
LatLng latLng = Util.stringToLatLng(latLngString);
Assert.assertEquals(Double.compare(latLng.latitude, 0), 0);
Assert.assertEquals(Double.compare(latLng.longitude, 0), 0);
}
}
Why we use Mocks?
The objective of unit testing is to exercise just one method at a time, but what
happens when that method depends on other things—hard-to-control things
such as the network, or a database.
The solution is the Mock object. It is simply a debug replacement for a real-
world object.
Mockito
Mockito is the way we mock objects in Android. As its developers say:
“Mockito is a mocking framework that tastes really good. It lets you write
beautiful tests with clean & simple API. Mockito doesn't give you hangover
because the tests are very readable and they produce clean verification
errors.”
• https://code.google.com/p/dexmaker/
• System property hack
Mockito and Android
//create Mock of server communication
final WeatherServerRequest weatherServerRequest =
Mockito.mock(WeatherServerRequest.class);
//stub the actual network call and return empty object
ServerResponse serverResponse = new ServerResponse();
Mockito.when(weatherServerRequest.getResponse()).thenReturn(serverResponse);
//create mock of the refresh-able and the observers subject
IRefreshable refreshable = Mockito.mock(IRefreshable.class);
ISubject subject = Mockito.mock(ISubject.class);
runWeatherWorkerThread(refreshable, subject, weatherServerRequest);
//verify if refresh-able start callback is called
Mockito.verify(refreshable).onStartRefresh();
//verify if the observers callback is called
Mockito.verify(subject).updateData(Mockito.anyMapOf(String.class,
ServerResponse.class));
//verify if refresh-able end callback is called
Mockito.verify(refreshable).onEndRefresh();
=+
Activity tests
ActivityInstrumentationTestCase2
This is the class which helps us test our Activities. It has direct reference to the
tested activity and you have the ability to run whole test or just parts of it in the
UI Thread.
@SmallTest
public void test_viewPagerHasAllLocations() throws Throwable {
//Creates the data fetcher mock and injects it to the Activity for every test
createDataFetcherMock();
runTestOnUiThread(new Runnable() {
@Override
public void run() {
//reinitialize activity with new data fetcher
getActivity().init();
}
});
//asserts if the view pager has the same number of items the data fetcher returned
Assert.assertEquals(3, mViewPager.getAdapter().getCount());
}
Robotium
o It is a lot easier to write our automation tests
o Helpful API for executing user actions
o Flexible results assertion
o Hybrid apps are supported
o We can use it in our Activity tests
Robotium in action
@LargeTest
public void test_addNewLocation() throws Throwable {
getInstrumentation().waitForIdleSync();
moveMapToPosition();
getInstrumentation().waitForIdleSync();
//gets the root view of the Activity
View rootView = getActivity().findViewById(android.R.id.content);
//long click in the center of the screen
mSolo.clickLongOnScreen(rootView.getWidth()/2, rootView.getHeight()/2);
getInstrumentation().waitForIdleSync();
//get first weather location
WeatherDataFetcher dataFetcher = getActivity().getDataFetcher();
List<WeatherLocation> weatherLocations = dataFetcher.getLocationsList();
Assert.assertEquals(1, weatherLocations.size());
//check if the location is the right one
WeatherLocation weatherLocation = weatherLocations.get(0);
Assert.assertEquals("Santa Monica, CA", weatherLocation.getLocationName());
//clears DB
dataFetcher.removeLocation(0);
}
Thank you!
Questions?
References
o https://developer.android.com
o https://code.google.com/p/robotium/
o https://github.com/mockito/mockito
o http://blog.gfader.com/2010/10/why-are-automated-tests-so-important.html
o http://media.pragprog.com/titles/utj/mockobjects.pdf
o http://www.embedded.com/design/prototyping-and-
development/4398723/The-mock-object-approach-to-test-driven-
development

Mais conteúdo relacionado

Mais procurados

Mais procurados (20)

Mockito intro
Mockito introMockito intro
Mockito intro
 
Stop Making Excuses and Start Testing Your JavaScript
Stop Making Excuses and Start Testing Your JavaScriptStop Making Excuses and Start Testing Your JavaScript
Stop Making Excuses and Start Testing Your JavaScript
 
Unit testing
Unit testingUnit testing
Unit testing
 
Junit 5 - Maior e melhor
Junit 5 - Maior e melhorJunit 5 - Maior e melhor
Junit 5 - Maior e melhor
 
Junit With Eclipse
Junit With EclipseJunit With Eclipse
Junit With Eclipse
 
JAVASCRIPT TDD(Test driven Development) & Qunit Tutorial
JAVASCRIPT TDD(Test driven Development) & Qunit TutorialJAVASCRIPT TDD(Test driven Development) & Qunit Tutorial
JAVASCRIPT TDD(Test driven Development) & Qunit Tutorial
 
Mockito
MockitoMockito
Mockito
 
Junit mockito and PowerMock in Java
Junit mockito and  PowerMock in JavaJunit mockito and  PowerMock in Java
Junit mockito and PowerMock in Java
 
1 aleksandr gritsevski - attd example using
1   aleksandr gritsevski - attd example using1   aleksandr gritsevski - attd example using
1 aleksandr gritsevski - attd example using
 
JUnit 5
JUnit 5JUnit 5
JUnit 5
 
JMockit
JMockitJMockit
JMockit
 
Junit, mockito, etc
Junit, mockito, etcJunit, mockito, etc
Junit, mockito, etc
 
An introduction to Google test framework
An introduction to Google test frameworkAn introduction to Google test framework
An introduction to Google test framework
 
Java Quiz - Meetup
Java Quiz - MeetupJava Quiz - Meetup
Java Quiz - Meetup
 
Unit testing with java
Unit testing with javaUnit testing with java
Unit testing with java
 
Tomasz Polanski - Automated mobile testing 2016 - Testing: why, when, how
Tomasz Polanski - Automated mobile testing 2016 - Testing: why, when, howTomasz Polanski - Automated mobile testing 2016 - Testing: why, when, how
Tomasz Polanski - Automated mobile testing 2016 - Testing: why, when, how
 
3 j unit
3 j unit3 j unit
3 j unit
 
JUNit Presentation
JUNit PresentationJUNit Presentation
JUNit Presentation
 
Junit and testNG
Junit and testNGJunit and testNG
Junit and testNG
 
Thread & concurrancy
Thread & concurrancyThread & concurrancy
Thread & concurrancy
 

Semelhante a Unit & Automation Testing in Android - Stanislav Gatsev, Melon

Grails unit testing
Grails unit testingGrails unit testing
Grails unit testingpleeps
 
Unit Testing on Android - Droidcon Berlin 2015
Unit Testing on Android - Droidcon Berlin 2015Unit Testing on Android - Droidcon Berlin 2015
Unit Testing on Android - Droidcon Berlin 2015Buşra Deniz, CSM
 
Hitchhiker's guide to Functional Testing
Hitchhiker's guide to Functional TestingHitchhiker's guide to Functional Testing
Hitchhiker's guide to Functional TestingWiebe Elsinga
 
Guide to the jungle of testing frameworks
Guide to the jungle of testing frameworksGuide to the jungle of testing frameworks
Guide to the jungle of testing frameworksTomáš Kypta
 
Testing in android
Testing in androidTesting in android
Testing in androidjtrindade
 
Android testing
Android testingAndroid testing
Android testingSean Tsai
 
比XML更好用的Java Annotation
比XML更好用的Java Annotation比XML更好用的Java Annotation
比XML更好用的Java Annotationjavatwo2011
 
Alexey Buzdin "Maslow's Pyramid of Android Testing"
Alexey Buzdin "Maslow's Pyramid of Android Testing"Alexey Buzdin "Maslow's Pyramid of Android Testing"
Alexey Buzdin "Maslow's Pyramid of Android Testing"IT Event
 
Thomas braun dependency-injection_with_robo_guice-presentation-final
Thomas braun dependency-injection_with_robo_guice-presentation-finalThomas braun dependency-injection_with_robo_guice-presentation-final
Thomas braun dependency-injection_with_robo_guice-presentation-finalDroidcon Berlin
 
The real beginner's guide to android testing
The real beginner's guide to android testingThe real beginner's guide to android testing
The real beginner's guide to android testingEric (Trung Dung) Nguyen
 
Google mock training
Google mock trainingGoogle mock training
Google mock trainingThierry Gayet
 
Unit testing in iOS featuring OCUnit, GHUnit & OCMock
Unit testing in iOS featuring OCUnit, GHUnit & OCMockUnit testing in iOS featuring OCUnit, GHUnit & OCMock
Unit testing in iOS featuring OCUnit, GHUnit & OCMockRobot Media
 
Automating Tactically vs Strategically SauceCon 2020
Automating Tactically vs Strategically SauceCon 2020Automating Tactically vs Strategically SauceCon 2020
Automating Tactically vs Strategically SauceCon 2020Alan Richardson
 
Junit4&testng presentation
Junit4&testng presentationJunit4&testng presentation
Junit4&testng presentationSanjib Dhar
 
2012 JDays Bad Tests Good Tests
2012 JDays Bad Tests Good Tests2012 JDays Bad Tests Good Tests
2012 JDays Bad Tests Good TestsTomek Kaczanowski
 
Testing Java Microservices Devoxx be 2017
Testing Java Microservices Devoxx be 2017Testing Java Microservices Devoxx be 2017
Testing Java Microservices Devoxx be 2017Alex Soto
 
33rd Degree 2013, Bad Tests, Good Tests
33rd Degree 2013, Bad Tests, Good Tests33rd Degree 2013, Bad Tests, Good Tests
33rd Degree 2013, Bad Tests, Good TestsTomek Kaczanowski
 
Dev fest kyoto_2021-flutter_test
Dev fest kyoto_2021-flutter_testDev fest kyoto_2021-flutter_test
Dev fest kyoto_2021-flutter_testMasanori Kato
 
Java performance
Java performanceJava performance
Java performanceSergey D
 

Semelhante a Unit & Automation Testing in Android - Stanislav Gatsev, Melon (20)

Grails unit testing
Grails unit testingGrails unit testing
Grails unit testing
 
Agile mobile
Agile mobileAgile mobile
Agile mobile
 
Unit Testing on Android - Droidcon Berlin 2015
Unit Testing on Android - Droidcon Berlin 2015Unit Testing on Android - Droidcon Berlin 2015
Unit Testing on Android - Droidcon Berlin 2015
 
Hitchhiker's guide to Functional Testing
Hitchhiker's guide to Functional TestingHitchhiker's guide to Functional Testing
Hitchhiker's guide to Functional Testing
 
Guide to the jungle of testing frameworks
Guide to the jungle of testing frameworksGuide to the jungle of testing frameworks
Guide to the jungle of testing frameworks
 
Testing in android
Testing in androidTesting in android
Testing in android
 
Android testing
Android testingAndroid testing
Android testing
 
比XML更好用的Java Annotation
比XML更好用的Java Annotation比XML更好用的Java Annotation
比XML更好用的Java Annotation
 
Alexey Buzdin "Maslow's Pyramid of Android Testing"
Alexey Buzdin "Maslow's Pyramid of Android Testing"Alexey Buzdin "Maslow's Pyramid of Android Testing"
Alexey Buzdin "Maslow's Pyramid of Android Testing"
 
Thomas braun dependency-injection_with_robo_guice-presentation-final
Thomas braun dependency-injection_with_robo_guice-presentation-finalThomas braun dependency-injection_with_robo_guice-presentation-final
Thomas braun dependency-injection_with_robo_guice-presentation-final
 
The real beginner's guide to android testing
The real beginner's guide to android testingThe real beginner's guide to android testing
The real beginner's guide to android testing
 
Google mock training
Google mock trainingGoogle mock training
Google mock training
 
Unit testing in iOS featuring OCUnit, GHUnit & OCMock
Unit testing in iOS featuring OCUnit, GHUnit & OCMockUnit testing in iOS featuring OCUnit, GHUnit & OCMock
Unit testing in iOS featuring OCUnit, GHUnit & OCMock
 
Automating Tactically vs Strategically SauceCon 2020
Automating Tactically vs Strategically SauceCon 2020Automating Tactically vs Strategically SauceCon 2020
Automating Tactically vs Strategically SauceCon 2020
 
Junit4&testng presentation
Junit4&testng presentationJunit4&testng presentation
Junit4&testng presentation
 
2012 JDays Bad Tests Good Tests
2012 JDays Bad Tests Good Tests2012 JDays Bad Tests Good Tests
2012 JDays Bad Tests Good Tests
 
Testing Java Microservices Devoxx be 2017
Testing Java Microservices Devoxx be 2017Testing Java Microservices Devoxx be 2017
Testing Java Microservices Devoxx be 2017
 
33rd Degree 2013, Bad Tests, Good Tests
33rd Degree 2013, Bad Tests, Good Tests33rd Degree 2013, Bad Tests, Good Tests
33rd Degree 2013, Bad Tests, Good Tests
 
Dev fest kyoto_2021-flutter_test
Dev fest kyoto_2021-flutter_testDev fest kyoto_2021-flutter_test
Dev fest kyoto_2021-flutter_test
 
Java performance
Java performanceJava performance
Java performance
 

Mais de beITconference

ADASTRA +1 or How YOU generate additional value in the project lifecycle - Пе...
ADASTRA +1 or How YOU generate additional value in the project lifecycle - Пе...ADASTRA +1 or How YOU generate additional value in the project lifecycle - Пе...
ADASTRA +1 or How YOU generate additional value in the project lifecycle - Пе...beITconference
 
NoSQL and Cloud Services - Philip Balinow, Comfo
NoSQL and Cloud Services -  Philip Balinow, ComfoNoSQL and Cloud Services -  Philip Balinow, Comfo
NoSQL and Cloud Services - Philip Balinow, ComfobeITconference
 
Mobile First with Angular.JS - Владимир Цветков, Obecto
Mobile First with Angular.JS - Владимир Цветков, ObectoMobile First with Angular.JS - Владимир Цветков, Obecto
Mobile First with Angular.JS - Владимир Цветков, ObectobeITconference
 
Уроците от работата ми по WordPress.com - Веселин Николов
Уроците от работата ми по WordPress.com - Веселин НиколовУроците от работата ми по WordPress.com - Веселин Николов
Уроците от работата ми по WordPress.com - Веселин НиколовbeITconference
 
Scrum Crash Course - Anatoli Iliev and Lyubomir Cholakov, Infragistics
Scrum Crash Course - Anatoli Iliev and Lyubomir Cholakov, InfragisticsScrum Crash Course - Anatoli Iliev and Lyubomir Cholakov, Infragistics
Scrum Crash Course - Anatoli Iliev and Lyubomir Cholakov, InfragisticsbeITconference
 
Развитие на финансовите приложения от транзакционни услуги към комплексно реш...
Развитие на финансовите приложения от транзакционни услуги към комплексно реш...Развитие на финансовите приложения от транзакционни услуги към комплексно реш...
Развитие на финансовите приложения от транзакционни услуги към комплексно реш...beITconference
 
The Web and The Social - Harry Birimirski, Smart IT
The Web and The Social - Harry Birimirski, Smart ITThe Web and The Social - Harry Birimirski, Smart IT
The Web and The Social - Harry Birimirski, Smart ITbeITconference
 

Mais de beITconference (7)

ADASTRA +1 or How YOU generate additional value in the project lifecycle - Пе...
ADASTRA +1 or How YOU generate additional value in the project lifecycle - Пе...ADASTRA +1 or How YOU generate additional value in the project lifecycle - Пе...
ADASTRA +1 or How YOU generate additional value in the project lifecycle - Пе...
 
NoSQL and Cloud Services - Philip Balinow, Comfo
NoSQL and Cloud Services -  Philip Balinow, ComfoNoSQL and Cloud Services -  Philip Balinow, Comfo
NoSQL and Cloud Services - Philip Balinow, Comfo
 
Mobile First with Angular.JS - Владимир Цветков, Obecto
Mobile First with Angular.JS - Владимир Цветков, ObectoMobile First with Angular.JS - Владимир Цветков, Obecto
Mobile First with Angular.JS - Владимир Цветков, Obecto
 
Уроците от работата ми по WordPress.com - Веселин Николов
Уроците от работата ми по WordPress.com - Веселин НиколовУроците от работата ми по WordPress.com - Веселин Николов
Уроците от работата ми по WordPress.com - Веселин Николов
 
Scrum Crash Course - Anatoli Iliev and Lyubomir Cholakov, Infragistics
Scrum Crash Course - Anatoli Iliev and Lyubomir Cholakov, InfragisticsScrum Crash Course - Anatoli Iliev and Lyubomir Cholakov, Infragistics
Scrum Crash Course - Anatoli Iliev and Lyubomir Cholakov, Infragistics
 
Развитие на финансовите приложения от транзакционни услуги към комплексно реш...
Развитие на финансовите приложения от транзакционни услуги към комплексно реш...Развитие на финансовите приложения от транзакционни услуги към комплексно реш...
Развитие на финансовите приложения от транзакционни услуги към комплексно реш...
 
The Web and The Social - Harry Birimirski, Smart IT
The Web and The Social - Harry Birimirski, Smart ITThe Web and The Social - Harry Birimirski, Smart IT
The Web and The Social - Harry Birimirski, Smart IT
 

Último

RACHEL-ANN M. TENIBRO PRODUCT RESEARCH PRESENTATION
RACHEL-ANN M. TENIBRO PRODUCT RESEARCH PRESENTATIONRACHEL-ANN M. TENIBRO PRODUCT RESEARCH PRESENTATION
RACHEL-ANN M. TENIBRO PRODUCT RESEARCH PRESENTATIONRachelAnnTenibroAmaz
 
Internship Presentation | PPT | CSE | SE
Internship Presentation | PPT | CSE | SEInternship Presentation | PPT | CSE | SE
Internship Presentation | PPT | CSE | SESaleh Ibne Omar
 
INDIAN GCP GUIDELINE. for Regulatory affair 1st sem CRR
INDIAN GCP GUIDELINE. for Regulatory  affair 1st sem CRRINDIAN GCP GUIDELINE. for Regulatory  affair 1st sem CRR
INDIAN GCP GUIDELINE. for Regulatory affair 1st sem CRRsarwankumar4524
 
THE COUNTRY WHO SOLVED THE WORLD_HOW CHINA LAUNCHED THE CIVILIZATION REVOLUTI...
THE COUNTRY WHO SOLVED THE WORLD_HOW CHINA LAUNCHED THE CIVILIZATION REVOLUTI...THE COUNTRY WHO SOLVED THE WORLD_HOW CHINA LAUNCHED THE CIVILIZATION REVOLUTI...
THE COUNTRY WHO SOLVED THE WORLD_HOW CHINA LAUNCHED THE CIVILIZATION REVOLUTI...漢銘 謝
 
proposal kumeneger edited.docx A kumeeger
proposal kumeneger edited.docx A kumeegerproposal kumeneger edited.docx A kumeeger
proposal kumeneger edited.docx A kumeegerkumenegertelayegrama
 
Application of GIS in Landslide Disaster Response.pptx
Application of GIS in Landslide Disaster Response.pptxApplication of GIS in Landslide Disaster Response.pptx
Application of GIS in Landslide Disaster Response.pptxRoquia Salam
 
cse-csp batch4 review-1.1.pptx cyber security
cse-csp batch4 review-1.1.pptx cyber securitycse-csp batch4 review-1.1.pptx cyber security
cse-csp batch4 review-1.1.pptx cyber securitysandeepnani2260
 
Testing and Development Challenges for Complex Cyber-Physical Systems: Insigh...
Testing and Development Challenges for Complex Cyber-Physical Systems: Insigh...Testing and Development Challenges for Complex Cyber-Physical Systems: Insigh...
Testing and Development Challenges for Complex Cyber-Physical Systems: Insigh...Sebastiano Panichella
 
General Elections Final Press Noteas per M
General Elections Final Press Noteas per MGeneral Elections Final Press Noteas per M
General Elections Final Press Noteas per MVidyaAdsule1
 
A Guide to Choosing the Ideal Air Cooler
A Guide to Choosing the Ideal Air CoolerA Guide to Choosing the Ideal Air Cooler
A Guide to Choosing the Ideal Air Coolerenquirieskenstar
 
05.02 MMC - Assignment 4 - Image Attribution Lovepreet.pptx
05.02 MMC - Assignment 4 - Image Attribution Lovepreet.pptx05.02 MMC - Assignment 4 - Image Attribution Lovepreet.pptx
05.02 MMC - Assignment 4 - Image Attribution Lovepreet.pptxerickamwana1
 
Quality by design.. ppt for RA (1ST SEM
Quality by design.. ppt for  RA (1ST SEMQuality by design.. ppt for  RA (1ST SEM
Quality by design.. ppt for RA (1ST SEMCharmi13
 
GESCO SE Press and Analyst Conference on Financial Results 2024
GESCO SE Press and Analyst Conference on Financial Results 2024GESCO SE Press and Analyst Conference on Financial Results 2024
GESCO SE Press and Analyst Conference on Financial Results 2024GESCO SE
 
Don't Miss Out: Strategies for Making the Most of the Ethena DigitalOpportunity
Don't Miss Out: Strategies for Making the Most of the Ethena DigitalOpportunityDon't Miss Out: Strategies for Making the Most of the Ethena DigitalOpportunity
Don't Miss Out: Strategies for Making the Most of the Ethena DigitalOpportunityApp Ethena
 
Engaging Eid Ul Fitr Presentation for Kindergartners.pptx
Engaging Eid Ul Fitr Presentation for Kindergartners.pptxEngaging Eid Ul Fitr Presentation for Kindergartners.pptx
Engaging Eid Ul Fitr Presentation for Kindergartners.pptxAsifArshad8
 
Chizaram's Women Tech Makers Deck. .pptx
Chizaram's Women Tech Makers Deck.  .pptxChizaram's Women Tech Makers Deck.  .pptx
Chizaram's Women Tech Makers Deck. .pptxogubuikealex
 
Testing with Fewer Resources: Toward Adaptive Approaches for Cost-effective ...
Testing with Fewer Resources:  Toward Adaptive Approaches for Cost-effective ...Testing with Fewer Resources:  Toward Adaptive Approaches for Cost-effective ...
Testing with Fewer Resources: Toward Adaptive Approaches for Cost-effective ...Sebastiano Panichella
 

Último (17)

RACHEL-ANN M. TENIBRO PRODUCT RESEARCH PRESENTATION
RACHEL-ANN M. TENIBRO PRODUCT RESEARCH PRESENTATIONRACHEL-ANN M. TENIBRO PRODUCT RESEARCH PRESENTATION
RACHEL-ANN M. TENIBRO PRODUCT RESEARCH PRESENTATION
 
Internship Presentation | PPT | CSE | SE
Internship Presentation | PPT | CSE | SEInternship Presentation | PPT | CSE | SE
Internship Presentation | PPT | CSE | SE
 
INDIAN GCP GUIDELINE. for Regulatory affair 1st sem CRR
INDIAN GCP GUIDELINE. for Regulatory  affair 1st sem CRRINDIAN GCP GUIDELINE. for Regulatory  affair 1st sem CRR
INDIAN GCP GUIDELINE. for Regulatory affair 1st sem CRR
 
THE COUNTRY WHO SOLVED THE WORLD_HOW CHINA LAUNCHED THE CIVILIZATION REVOLUTI...
THE COUNTRY WHO SOLVED THE WORLD_HOW CHINA LAUNCHED THE CIVILIZATION REVOLUTI...THE COUNTRY WHO SOLVED THE WORLD_HOW CHINA LAUNCHED THE CIVILIZATION REVOLUTI...
THE COUNTRY WHO SOLVED THE WORLD_HOW CHINA LAUNCHED THE CIVILIZATION REVOLUTI...
 
proposal kumeneger edited.docx A kumeeger
proposal kumeneger edited.docx A kumeegerproposal kumeneger edited.docx A kumeeger
proposal kumeneger edited.docx A kumeeger
 
Application of GIS in Landslide Disaster Response.pptx
Application of GIS in Landslide Disaster Response.pptxApplication of GIS in Landslide Disaster Response.pptx
Application of GIS in Landslide Disaster Response.pptx
 
cse-csp batch4 review-1.1.pptx cyber security
cse-csp batch4 review-1.1.pptx cyber securitycse-csp batch4 review-1.1.pptx cyber security
cse-csp batch4 review-1.1.pptx cyber security
 
Testing and Development Challenges for Complex Cyber-Physical Systems: Insigh...
Testing and Development Challenges for Complex Cyber-Physical Systems: Insigh...Testing and Development Challenges for Complex Cyber-Physical Systems: Insigh...
Testing and Development Challenges for Complex Cyber-Physical Systems: Insigh...
 
General Elections Final Press Noteas per M
General Elections Final Press Noteas per MGeneral Elections Final Press Noteas per M
General Elections Final Press Noteas per M
 
A Guide to Choosing the Ideal Air Cooler
A Guide to Choosing the Ideal Air CoolerA Guide to Choosing the Ideal Air Cooler
A Guide to Choosing the Ideal Air Cooler
 
05.02 MMC - Assignment 4 - Image Attribution Lovepreet.pptx
05.02 MMC - Assignment 4 - Image Attribution Lovepreet.pptx05.02 MMC - Assignment 4 - Image Attribution Lovepreet.pptx
05.02 MMC - Assignment 4 - Image Attribution Lovepreet.pptx
 
Quality by design.. ppt for RA (1ST SEM
Quality by design.. ppt for  RA (1ST SEMQuality by design.. ppt for  RA (1ST SEM
Quality by design.. ppt for RA (1ST SEM
 
GESCO SE Press and Analyst Conference on Financial Results 2024
GESCO SE Press and Analyst Conference on Financial Results 2024GESCO SE Press and Analyst Conference on Financial Results 2024
GESCO SE Press and Analyst Conference on Financial Results 2024
 
Don't Miss Out: Strategies for Making the Most of the Ethena DigitalOpportunity
Don't Miss Out: Strategies for Making the Most of the Ethena DigitalOpportunityDon't Miss Out: Strategies for Making the Most of the Ethena DigitalOpportunity
Don't Miss Out: Strategies for Making the Most of the Ethena DigitalOpportunity
 
Engaging Eid Ul Fitr Presentation for Kindergartners.pptx
Engaging Eid Ul Fitr Presentation for Kindergartners.pptxEngaging Eid Ul Fitr Presentation for Kindergartners.pptx
Engaging Eid Ul Fitr Presentation for Kindergartners.pptx
 
Chizaram's Women Tech Makers Deck. .pptx
Chizaram's Women Tech Makers Deck.  .pptxChizaram's Women Tech Makers Deck.  .pptx
Chizaram's Women Tech Makers Deck. .pptx
 
Testing with Fewer Resources: Toward Adaptive Approaches for Cost-effective ...
Testing with Fewer Resources:  Toward Adaptive Approaches for Cost-effective ...Testing with Fewer Resources:  Toward Adaptive Approaches for Cost-effective ...
Testing with Fewer Resources: Toward Adaptive Approaches for Cost-effective ...
 

Unit & Automation Testing in Android - Stanislav Gatsev, Melon

  • 1. Unit and Automation Testing on Android Stanislav Gatsev Android Team Lead, Melon Inc.
  • 2. Who am I? Stanislav Gatsev Android Team Lead +359 89 891 4481 stanislav.gatsev@melontech.com http://www.melon.bg
  • 3. What is Android? o World's most popular mobile platform o Every day another million users power up their Android devices for the first time o Using Android SDK we can develop software for almost everything from smartphones and tablets to glasses, watches, TVs and even cars.
  • 4. Why we automate testing? o We save time !!! o We improve our code quality o We support live documentation o We run our regression tests o We fight fragmentation
  • 6. What Can We Test? o We can test our logic, algorithms, calculations o We can test our UI and navigation logic o We can test IO operations, database and network operations o And more... @SmallTest public void test_addOperatorInJava() throws Exception { Assert.assertEquals(4, 2 + 2); Assert.assertEquals(27, 25 + 2); } @SmallTest public void test_FieldsAreVisible() { ViewAsserts.assertOnScreen(mRootView, mEmailEditText); ViewAsserts.assertOnScreen(mRootView, mPasswordEditText); ViewAsserts.assertOnScreen(mRootView, mLoginActionLayout); }
  • 7. How we automate testing? o We use JUnit o We mock our objects o We are using activity testing framework o We click with Robotium
  • 8. JUnit and Android We can use the JUnit TestCase class to do unit testing on a class that doesn't call Android APIs. TestCase is also the base class for AndroidTestCase, which we can use to test Android-dependent objects. Besides providing the JUnit framework, AndroidTestCase offers Android-specific setup, teardown, and helper methods. public class UtilTests extends AndroidTestCase { @SmallTest public void test_StringToLatLngValidValues() throws Exception { String latLngString = "34.009555,-118.497072"; LatLng latLng = Util.stringToLatLng(latLngString); Assert.assertEquals(Double.compare(latLng.latitude, 34.009555), 0); Assert.assertEquals(Double.compare(latLng.longitude, -118.497072), 0); } @SmallTest public void test_StringToLatLngValidInvalues() throws Exception { String latLngString = "34.009555,-a118.497072"; LatLng latLng = Util.stringToLatLng(latLngString); Assert.assertEquals(Double.compare(latLng.latitude, 0), 0); Assert.assertEquals(Double.compare(latLng.longitude, 0), 0); } }
  • 9. Why we use Mocks? The objective of unit testing is to exercise just one method at a time, but what happens when that method depends on other things—hard-to-control things such as the network, or a database. The solution is the Mock object. It is simply a debug replacement for a real- world object.
  • 10. Mockito Mockito is the way we mock objects in Android. As its developers say: “Mockito is a mocking framework that tastes really good. It lets you write beautiful tests with clean & simple API. Mockito doesn't give you hangover because the tests are very readable and they produce clean verification errors.” • https://code.google.com/p/dexmaker/ • System property hack
  • 11. Mockito and Android //create Mock of server communication final WeatherServerRequest weatherServerRequest = Mockito.mock(WeatherServerRequest.class); //stub the actual network call and return empty object ServerResponse serverResponse = new ServerResponse(); Mockito.when(weatherServerRequest.getResponse()).thenReturn(serverResponse); //create mock of the refresh-able and the observers subject IRefreshable refreshable = Mockito.mock(IRefreshable.class); ISubject subject = Mockito.mock(ISubject.class); runWeatherWorkerThread(refreshable, subject, weatherServerRequest); //verify if refresh-able start callback is called Mockito.verify(refreshable).onStartRefresh(); //verify if the observers callback is called Mockito.verify(subject).updateData(Mockito.anyMapOf(String.class, ServerResponse.class)); //verify if refresh-able end callback is called Mockito.verify(refreshable).onEndRefresh(); =+
  • 12. Activity tests ActivityInstrumentationTestCase2 This is the class which helps us test our Activities. It has direct reference to the tested activity and you have the ability to run whole test or just parts of it in the UI Thread. @SmallTest public void test_viewPagerHasAllLocations() throws Throwable { //Creates the data fetcher mock and injects it to the Activity for every test createDataFetcherMock(); runTestOnUiThread(new Runnable() { @Override public void run() { //reinitialize activity with new data fetcher getActivity().init(); } }); //asserts if the view pager has the same number of items the data fetcher returned Assert.assertEquals(3, mViewPager.getAdapter().getCount()); }
  • 13. Robotium o It is a lot easier to write our automation tests o Helpful API for executing user actions o Flexible results assertion o Hybrid apps are supported o We can use it in our Activity tests
  • 14. Robotium in action @LargeTest public void test_addNewLocation() throws Throwable { getInstrumentation().waitForIdleSync(); moveMapToPosition(); getInstrumentation().waitForIdleSync(); //gets the root view of the Activity View rootView = getActivity().findViewById(android.R.id.content); //long click in the center of the screen mSolo.clickLongOnScreen(rootView.getWidth()/2, rootView.getHeight()/2); getInstrumentation().waitForIdleSync(); //get first weather location WeatherDataFetcher dataFetcher = getActivity().getDataFetcher(); List<WeatherLocation> weatherLocations = dataFetcher.getLocationsList(); Assert.assertEquals(1, weatherLocations.size()); //check if the location is the right one WeatherLocation weatherLocation = weatherLocations.get(0); Assert.assertEquals("Santa Monica, CA", weatherLocation.getLocationName()); //clears DB dataFetcher.removeLocation(0); }
  • 16. References o https://developer.android.com o https://code.google.com/p/robotium/ o https://github.com/mockito/mockito o http://blog.gfader.com/2010/10/why-are-automated-tests-so-important.html o http://media.pragprog.com/titles/utj/mockobjects.pdf o http://www.embedded.com/design/prototyping-and- development/4398723/The-mock-object-approach-to-test-driven- development