SlideShare une entreprise Scribd logo
1  sur  23
Télécharger pour lire hors ligne
Best Practice:
Unit Testing in
Mobile AppsIndonesia
Jakarta, July 2017
Fandy Gotama
2
What To Do Before Writing Unit Test?
- Refactor your code,● You have legacy code?, Refactor it
● For a new project, use clean architecture approaches
● Convince yourself and your team, be consistent!
● Convince your BOSS!!, or should I?
3
● Do Test Review instead of Code Review
● Understanding their intent
● Communication
Change Your Team Behaviour
4
@Test
public void testGenerateDeviceToken() throws NoSuchAlgorithmException {
String ANY_DEVICE_ID = "123";
Generator generator = new Generator();
String token = generator.generateOAuthDeviceToken(ANY_DEVICE_ID);
Assert.assertEquals(“0bde9a580f199bd6856cc578", token);
}
5
@Test
public void testCategoryTableCreatedSuccessfully() {
mDatabaseHelper =
new CategorySQLiteDatabaseHelper(
RuntimeEnvironment.application, DB_NAME, DB_VERSION);
SQLiteDatabase db = mDatabaseHelper.getReadableDatabase();
Cursor cursor = db.rawQuery(
"SELECT * FROM sqlite_master " +
"WHERE type='table' " +
"AND name = '" + Category.TABLE_NAME +"'", null);
assertEquals(1, cursor.getCount());
}
6
Unit testing is a software development process in which the
smallest testable parts of an application, called units, are
individually and independently scrutinized for proper
operation. Unit testing can be done manually but is often
automated.
http://searchsoftwarequality.techtarget.com/definition/unit-testing
What is Unit Test?
7
● Trustworthy
● Maintainable
● Readable
Best Practice - Writing Good Unit Test
http://osherove.com/blog/2012/9/17/readable-maintainable-trustworthy-unit
-tests-in-java.html
8
@Test
public void testTransformApiResponseToModel() {
DataResponse response = mockResponse();
DataMapper mapper = new DataMapper();
for (CategoryResponse category : response.results) {
CategoryModel model = mapper.transform(category);
Assert.assertEquals(category.id, model.id);
}
}
9
@Test
public void testProductIsExpired() {
long tomorrowInMillis = System.currentTimeMillis() + 86410000;
boolean isExpired = Product.checkExpiration(tomorrowInMillis);
Assert.assertEquals(true, isExpired);
}
10
● Test driven
● Avoid logic in test
Trustworthy
11
@Test
public void testTransformWithDefaultParamValueForPriceAndCondition() {
RequestModel requestModel = mockRequestWithEmptyCondition();
DataRequest request = mMapper.transform(requestModel);
Assert.assertEquals("bekas", request.params.get("condition"));
Assert.assertEquals("[price, 0]", request.params.get("price").toString());
}
12
● Do not test private / protected methods
● Do not run test from another test
● Test one thing only
● Test can be run in any order
Maintainable
13
@Test
public void testCalculateTotalAmount() throws Exception {
double anyPrice = 10000;
Calculation spyCalculation = spy(new Calculation());
Checkout checkout = new Checkout();
checkout.runCalculation(anyPrice, spyCalculation);
verify(spyCalculation).calculateDiscount();
verify(spyCalculation).addTax();
verify(spyCalculation).addShippingPrice();
verify(spyCalculation).updateAmount();
Assert.assertEquals(15000, checkout.getAmount());
}
14
● Avoid testing internal works if it’s not important
● Only “verify” if that’s the only way to test your code
Maintainable
15
@Test
public void testGetAge() {
int age = 24;
Permission permission = new Permission();
boolean isHavePermissionToEnter = permission.checkAge(age);
Assert.assertEquals(true, isHavePermissionToEnter);
}
16
● Unit Test class name
● No magic variable
● Structure
Readable
17
Building Unit Test on Mobile Apps
18
public class MessagePresenter {
private final EmailService mService = new EmailService();
public void sendMessage(Context context, String message, String receiver) {
mService.send(message, receiver);
((MessageActivity) context).showLoading();
}
}
19
public class MessagePresenter {
private final MessageServiceInterface mService;
private final View mView;
public MessagePresenter(MessageServiceInterface service, View view) {
mView = view;
mService = service;
}
public void sendMessage(String message, String receiver) {
mService.send(message, receiver);
mView.showLoading();
}
public interface View {
void showLoading();
}
}
20
● Dependency Injection
● Loosely coupled
● Do not abuse static class
● Single responsibility principle
Building Unit Test on Mobile Apps
21
DEMO
https://github.com/CommunityShareCode/UnitTesting
22
Thank You
23
● http://artofunittesting.com/java/
● http://www.journaldev.com/2394/java-dependency-injection
-design-pattern-example-tutorial
● http://blog.stevensanderson.com/2009/08/24/writing-great-
unit-tests-best-and-worst-practises/
● http://osherove.com/blog/2012/9/17/readable-maintainable-
trustworthy-unit-tests-in-java.html
● http://searchsoftwarequality.techtarget.com/definition/unit-t
esting
● https://blog.pragmatists.com/test-doubles-fakes-mocks-and
-stubs-1a7491dfa3da

Contenu connexe

Tendances

Grails Spock Testing
Grails Spock TestingGrails Spock Testing
Grails Spock Testing
TO THE NEW | Technology
 
Advance unittest
Advance unittestAdvance unittest
Advance unittest
Reza Arbabi
 
Unit testing best practices
Unit testing best practicesUnit testing best practices
Unit testing best practices
nickokiss
 

Tendances (20)

Understanding JavaScript Testing
Understanding JavaScript TestingUnderstanding JavaScript Testing
Understanding JavaScript Testing
 
iOS Unit Testing
iOS Unit TestingiOS Unit Testing
iOS Unit Testing
 
Unit testing with JUnit
Unit testing with JUnitUnit testing with JUnit
Unit testing with JUnit
 
Best practices unit testing
Best practices unit testing Best practices unit testing
Best practices unit testing
 
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
 
Automated Unit Testing
Automated Unit TestingAutomated Unit Testing
Automated Unit Testing
 
Grails unit testing
Grails unit testingGrails unit testing
Grails unit testing
 
Unit test-using-spock in Grails
Unit test-using-spock in GrailsUnit test-using-spock in Grails
Unit test-using-spock in Grails
 
Hitchhiker's guide to Functional Testing
Hitchhiker's guide to Functional TestingHitchhiker's guide to Functional Testing
Hitchhiker's guide to Functional Testing
 
Grails Spock Testing
Grails Spock TestingGrails Spock Testing
Grails Spock Testing
 
Advance unittest
Advance unittestAdvance unittest
Advance unittest
 
Testing with VS2010 - A Bugs Life
Testing with VS2010 - A Bugs LifeTesting with VS2010 - A Bugs Life
Testing with VS2010 - A Bugs Life
 
Unit Testing in iOS
Unit Testing in iOSUnit Testing in iOS
Unit Testing in iOS
 
JavaScript Unit Testing with an Angular 5.x Use Case 101
JavaScript Unit Testing with an Angular 5.x Use Case 101JavaScript Unit Testing with an Angular 5.x Use Case 101
JavaScript Unit Testing with an Angular 5.x Use Case 101
 
Unit testing best practices
Unit testing best practicesUnit testing best practices
Unit testing best practices
 
Testacular
TestacularTestacular
Testacular
 
All about unit testing using (power) mock
All about unit testing using (power) mockAll about unit testing using (power) mock
All about unit testing using (power) mock
 
JUNit Presentation
JUNit PresentationJUNit Presentation
JUNit Presentation
 
Presentation Unit Testing process
Presentation Unit Testing processPresentation Unit Testing process
Presentation Unit Testing process
 
Unit testing
Unit testingUnit testing
Unit testing
 

Similaire à "Unit Testing for Mobile App" by Fandy Gotama (OLX Indonesia)

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
Robot Media
 

Similaire à "Unit Testing for Mobile App" by Fandy Gotama (OLX Indonesia) (20)

Developer Test - Things to Know
Developer Test - Things to KnowDeveloper Test - Things to Know
Developer Test - Things to Know
 
How to write clean tests
How to write clean testsHow to write clean tests
How to write clean tests
 
Unit testing patterns for concurrent code
Unit testing patterns for concurrent codeUnit testing patterns for concurrent code
Unit testing patterns for concurrent code
 
Test driven development
Test driven developmentTest driven development
Test driven development
 
Unit testing basic
Unit testing basicUnit testing basic
Unit testing basic
 
The secret unit testing tools no one has ever told you about
The secret unit testing tools no one has ever told you aboutThe secret unit testing tools no one has ever told you about
The secret unit testing tools no one has ever told you about
 
We Are All Testers Now: The Testing Pyramid and Front-End Development
We Are All Testers Now: The Testing Pyramid and Front-End DevelopmentWe Are All Testers Now: The Testing Pyramid and Front-End Development
We Are All Testers Now: The Testing Pyramid and Front-End Development
 
淺談高效撰寫單元測試
淺談高效撰寫單元測試淺談高效撰寫單元測試
淺談高效撰寫單元測試
 
Unit testing
Unit testingUnit testing
Unit testing
 
Scrum Gathering 2012 Shanghai_工程实践与技术卓越分会场:how to write unit test for new cod...
Scrum Gathering 2012 Shanghai_工程实践与技术卓越分会场:how to write unit test for new cod...Scrum Gathering 2012 Shanghai_工程实践与技术卓越分会场:how to write unit test for new cod...
Scrum Gathering 2012 Shanghai_工程实践与技术卓越分会场:how to write unit test for new cod...
 
Android testing
Android testingAndroid testing
Android testing
 
Solit 2013, Автоматизация тестирования сложных систем: mixed mode automated t...
Solit 2013, Автоматизация тестирования сложных систем: mixed mode automated t...Solit 2013, Автоматизация тестирования сложных систем: mixed mode automated t...
Solit 2013, Автоматизация тестирования сложных систем: mixed mode automated t...
 
Secret unit testing tools no one ever told you about
Secret unit testing tools no one ever told you aboutSecret unit testing tools no one ever told you about
Secret unit testing tools no one ever told you about
 
Testing Spring Applications
Testing Spring ApplicationsTesting Spring Applications
Testing Spring Applications
 
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
 
Unit Testing - The Whys, Whens and Hows
Unit Testing - The Whys, Whens and HowsUnit Testing - The Whys, Whens and Hows
Unit Testing - The Whys, Whens and Hows
 
The secret unit testing tools no one ever told you about
The secret unit testing tools no one ever told you aboutThe secret unit testing tools no one ever told you about
The secret unit testing tools no one ever told you about
 
Mockito intro
Mockito introMockito intro
Mockito intro
 
Testing, Performance Analysis, and jQuery 1.4
Testing, Performance Analysis, and jQuery 1.4Testing, Performance Analysis, and jQuery 1.4
Testing, Performance Analysis, and jQuery 1.4
 
Describe's Full of It's
Describe's Full of It'sDescribe's Full of It's
Describe's Full of It's
 

Plus de Tech in Asia ID

Plus de Tech in Asia ID (20)

Sesi Tech in Asia PDC'21.pdf
Sesi Tech in Asia PDC'21.pdfSesi Tech in Asia PDC'21.pdf
Sesi Tech in Asia PDC'21.pdf
 
"ILO's Work on Skills Development" by Project Coordinators International Labo...
"ILO's Work on Skills Development" by Project Coordinators International Labo..."ILO's Work on Skills Development" by Project Coordinators International Labo...
"ILO's Work on Skills Development" by Project Coordinators International Labo...
 
"Women in STEM: Leveraging Talent in ICT Sector" by Maya Juwita (Executive Di...
"Women in STEM: Leveraging Talent in ICT Sector" by Maya Juwita (Executive Di..."Women in STEM: Leveraging Talent in ICT Sector" by Maya Juwita (Executive Di...
"Women in STEM: Leveraging Talent in ICT Sector" by Maya Juwita (Executive Di...
 
Laporan Kondisi Pendanaan Startup di Indonesia Kuartal Ketiga Tahun 2018
Laporan Kondisi Pendanaan Startup di Indonesia Kuartal Ketiga Tahun 2018Laporan Kondisi Pendanaan Startup di Indonesia Kuartal Ketiga Tahun 2018
Laporan Kondisi Pendanaan Startup di Indonesia Kuartal Ketiga Tahun 2018
 
LinkedIn Pitch Deck
LinkedIn Pitch DeckLinkedIn Pitch Deck
LinkedIn Pitch Deck
 
Laporan Kondisi Pendanaan Startup di Indonesia Kuartal Kedua Tahun 2018
Laporan Kondisi Pendanaan Startup di Indonesia Kuartal Kedua Tahun 2018Laporan Kondisi Pendanaan Startup di Indonesia Kuartal Kedua Tahun 2018
Laporan Kondisi Pendanaan Startup di Indonesia Kuartal Kedua Tahun 2018
 
Laporan Kondisi Pendanaan Startup di Indonesia Kuartal Pertama Tahun 2018
Laporan Kondisi Pendanaan Startup di Indonesia Kuartal Pertama Tahun 2018Laporan Kondisi Pendanaan Startup di Indonesia Kuartal Pertama Tahun 2018
Laporan Kondisi Pendanaan Startup di Indonesia Kuartal Pertama Tahun 2018
 
Laporan Kondisi Pendanaan Startup di Indonesia Tahun 2017
Laporan Kondisi Pendanaan Startup di Indonesia Tahun 2017Laporan Kondisi Pendanaan Startup di Indonesia Tahun 2017
Laporan Kondisi Pendanaan Startup di Indonesia Tahun 2017
 
"Less Painful iOS Development" by Samuel Edwin (Tokopedia)
"Less Painful iOS Development" by Samuel Edwin (Tokopedia)"Less Painful iOS Development" by Samuel Edwin (Tokopedia)
"Less Painful iOS Development" by Samuel Edwin (Tokopedia)
 
"Product Development Story Loket.com" by Aruna Laksana (Loket.com)
"Product Development Story Loket.com" by Aruna Laksana (Loket.com)"Product Development Story Loket.com" by Aruna Laksana (Loket.com)
"Product Development Story Loket.com" by Aruna Laksana (Loket.com)
 
"Making Data Actionable" by Budiman Rusly (KMK Online)
"Making Data Actionable" by Budiman Rusly (KMK Online)"Making Data Actionable" by Budiman Rusly (KMK Online)
"Making Data Actionable" by Budiman Rusly (KMK Online)
 
"DOKU under the hood : Infrastructure and Cloud Services Technology" by M. T...
"DOKU under the hood :  Infrastructure and Cloud Services Technology" by M. T..."DOKU under the hood :  Infrastructure and Cloud Services Technology" by M. T...
"DOKU under the hood : Infrastructure and Cloud Services Technology" by M. T...
 
Citcall : Real-Time User Verification with Missed-Call Based OTP
Citcall : Real-Time User Verification with Missed-Call Based OTPCitcall : Real-Time User Verification with Missed-Call Based OTP
Citcall : Real-Time User Verification with Missed-Call Based OTP
 
"Functional Programming in a Nutshell" by Adityo Pratomo (Froyo Framework)
"Functional Programming in a Nutshell" by Adityo Pratomo (Froyo Framework)"Functional Programming in a Nutshell" by Adityo Pratomo (Froyo Framework)
"Functional Programming in a Nutshell" by Adityo Pratomo (Froyo Framework)
 
"Building High Performance Search Feature" by Setyo Legowo (UrbanIndo)
"Building High Performance Search Feature" by Setyo Legowo (UrbanIndo)"Building High Performance Search Feature" by Setyo Legowo (UrbanIndo)
"Building High Performance Search Feature" by Setyo Legowo (UrbanIndo)
 
"Building Effective Developer-Designer Relationships" by Ifnu Bima (Blibli.com)
"Building Effective Developer-Designer Relationships" by Ifnu Bima (Blibli.com)"Building Effective Developer-Designer Relationships" by Ifnu Bima (Blibli.com)
"Building Effective Developer-Designer Relationships" by Ifnu Bima (Blibli.com)
 
"Data Informed vs Data Driven" by Casper Sermsuksan (Kulina)
"Data Informed vs Data Driven" by Casper Sermsuksan (Kulina)"Data Informed vs Data Driven" by Casper Sermsuksan (Kulina)
"Data Informed vs Data Driven" by Casper Sermsuksan (Kulina)
 
"Planning Your Analytics Implementation" by Bachtiar Rifai (Kofera Technology)
"Planning Your Analytics Implementation" by Bachtiar Rifai (Kofera Technology)"Planning Your Analytics Implementation" by Bachtiar Rifai (Kofera Technology)
"Planning Your Analytics Implementation" by Bachtiar Rifai (Kofera Technology)
 
"How To Build and Lead a Winning Data Team" by Cahyo Listyanto (Bizzy.co.id)
"How To Build and Lead a Winning Data Team" by Cahyo Listyanto (Bizzy.co.id)"How To Build and Lead a Winning Data Team" by Cahyo Listyanto (Bizzy.co.id)
"How To Build and Lead a Winning Data Team" by Cahyo Listyanto (Bizzy.co.id)
 
"How Scrum Motivates People" by Rudy Rahadian (XL Axiata)
"How Scrum Motivates People" by Rudy Rahadian (XL Axiata)"How Scrum Motivates People" by Rudy Rahadian (XL Axiata)
"How Scrum Motivates People" by Rudy Rahadian (XL Axiata)
 

Dernier

Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Victor Rentea
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
?#DUbAI#??##{{(☎️+971_581248768%)**%*]'#abortion pills for sale in dubai@
 

Dernier (20)

"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
 
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUKSpring Boot vs Quarkus the ultimate battle - DevoxxUK
Spring Boot vs Quarkus the ultimate battle - DevoxxUK
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWEREMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
EMPOWERMENT TECHNOLOGY GRADE 11 QUARTER 2 REVIEWER
 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistan
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
Apidays New York 2024 - Accelerating FinTech Innovation by Vasa Krishnan, Fin...
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 

"Unit Testing for Mobile App" by Fandy Gotama (OLX Indonesia)

  • 1. Best Practice: Unit Testing in Mobile AppsIndonesia Jakarta, July 2017 Fandy Gotama
  • 2. 2 What To Do Before Writing Unit Test? - Refactor your code,● You have legacy code?, Refactor it ● For a new project, use clean architecture approaches ● Convince yourself and your team, be consistent! ● Convince your BOSS!!, or should I?
  • 3. 3 ● Do Test Review instead of Code Review ● Understanding their intent ● Communication Change Your Team Behaviour
  • 4. 4 @Test public void testGenerateDeviceToken() throws NoSuchAlgorithmException { String ANY_DEVICE_ID = "123"; Generator generator = new Generator(); String token = generator.generateOAuthDeviceToken(ANY_DEVICE_ID); Assert.assertEquals(“0bde9a580f199bd6856cc578", token); }
  • 5. 5 @Test public void testCategoryTableCreatedSuccessfully() { mDatabaseHelper = new CategorySQLiteDatabaseHelper( RuntimeEnvironment.application, DB_NAME, DB_VERSION); SQLiteDatabase db = mDatabaseHelper.getReadableDatabase(); Cursor cursor = db.rawQuery( "SELECT * FROM sqlite_master " + "WHERE type='table' " + "AND name = '" + Category.TABLE_NAME +"'", null); assertEquals(1, cursor.getCount()); }
  • 6. 6 Unit testing is a software development process in which the smallest testable parts of an application, called units, are individually and independently scrutinized for proper operation. Unit testing can be done manually but is often automated. http://searchsoftwarequality.techtarget.com/definition/unit-testing What is Unit Test?
  • 7. 7 ● Trustworthy ● Maintainable ● Readable Best Practice - Writing Good Unit Test http://osherove.com/blog/2012/9/17/readable-maintainable-trustworthy-unit -tests-in-java.html
  • 8. 8 @Test public void testTransformApiResponseToModel() { DataResponse response = mockResponse(); DataMapper mapper = new DataMapper(); for (CategoryResponse category : response.results) { CategoryModel model = mapper.transform(category); Assert.assertEquals(category.id, model.id); } }
  • 9. 9 @Test public void testProductIsExpired() { long tomorrowInMillis = System.currentTimeMillis() + 86410000; boolean isExpired = Product.checkExpiration(tomorrowInMillis); Assert.assertEquals(true, isExpired); }
  • 10. 10 ● Test driven ● Avoid logic in test Trustworthy
  • 11. 11 @Test public void testTransformWithDefaultParamValueForPriceAndCondition() { RequestModel requestModel = mockRequestWithEmptyCondition(); DataRequest request = mMapper.transform(requestModel); Assert.assertEquals("bekas", request.params.get("condition")); Assert.assertEquals("[price, 0]", request.params.get("price").toString()); }
  • 12. 12 ● Do not test private / protected methods ● Do not run test from another test ● Test one thing only ● Test can be run in any order Maintainable
  • 13. 13 @Test public void testCalculateTotalAmount() throws Exception { double anyPrice = 10000; Calculation spyCalculation = spy(new Calculation()); Checkout checkout = new Checkout(); checkout.runCalculation(anyPrice, spyCalculation); verify(spyCalculation).calculateDiscount(); verify(spyCalculation).addTax(); verify(spyCalculation).addShippingPrice(); verify(spyCalculation).updateAmount(); Assert.assertEquals(15000, checkout.getAmount()); }
  • 14. 14 ● Avoid testing internal works if it’s not important ● Only “verify” if that’s the only way to test your code Maintainable
  • 15. 15 @Test public void testGetAge() { int age = 24; Permission permission = new Permission(); boolean isHavePermissionToEnter = permission.checkAge(age); Assert.assertEquals(true, isHavePermissionToEnter); }
  • 16. 16 ● Unit Test class name ● No magic variable ● Structure Readable
  • 17. 17 Building Unit Test on Mobile Apps
  • 18. 18 public class MessagePresenter { private final EmailService mService = new EmailService(); public void sendMessage(Context context, String message, String receiver) { mService.send(message, receiver); ((MessageActivity) context).showLoading(); } }
  • 19. 19 public class MessagePresenter { private final MessageServiceInterface mService; private final View mView; public MessagePresenter(MessageServiceInterface service, View view) { mView = view; mService = service; } public void sendMessage(String message, String receiver) { mService.send(message, receiver); mView.showLoading(); } public interface View { void showLoading(); } }
  • 20. 20 ● Dependency Injection ● Loosely coupled ● Do not abuse static class ● Single responsibility principle Building Unit Test on Mobile Apps
  • 23. 23 ● http://artofunittesting.com/java/ ● http://www.journaldev.com/2394/java-dependency-injection -design-pattern-example-tutorial ● http://blog.stevensanderson.com/2009/08/24/writing-great- unit-tests-best-and-worst-practises/ ● http://osherove.com/blog/2012/9/17/readable-maintainable- trustworthy-unit-tests-in-java.html ● http://searchsoftwarequality.techtarget.com/definition/unit-t esting ● https://blog.pragmatists.com/test-doubles-fakes-mocks-and -stubs-1a7491dfa3da