SlideShare a Scribd company logo
Building Maintainable 
Android Applications 
! 
Kevin Schultz (@kevinrschultz) 
DroidCon NYC 2014 
! 
kevinrschultz.com 
github.com/krschultz/AndroidWeatherBuoyDemo
Apps vs Applications
Building Maintainable Android Apps (DroidCon NYC 2014)
Treading Water 
Time spent on features dwindles 
Infrequent releases due to high 
QA costs 
Heisenbug whack-a-mole 
Fear of change 
Infrastructure 
Bugs 
Features
Drowning 
Platform Changes 
Business Pivot 
Competitors 
Panic 
How many regressions will 
you cause when 
implementing Material 
Design?
Refactor! Rewrite!
The codebase is a mess!
Unlikely to be better next time 
Clean code is necessary but insufficient for 
maintainability 
We are state of the art today, what about next year? 
Why do Android apps always seem to become 
unmaintainable?
Android was initially for Apps 
Documentation & samples are small scale 
Old build system was deficient 
Testing tools are still sub-par 
Framework was not designed for testability 
Performance trumped clean code
You must build a system to 
counter software entropy
Software Entropy 
“As a system is modified, its disorder, or entropy, always 
increases. This is known as software entropy.” 
- Ivar Jacobson 
“Legacy code is code without tests” 
- Michael Feathers
System 
Espresso 
Functional Tests 
UI Tests 
Build 
Unit Tests App 
CI Server
System Thinking 
How will each component be tested over its lifetime? 
What leads to the minimum cost of development 
including QA time? 
If a library makes it easy to add a feature but harder to 
test, is it worth it? 
If a tool breaks CI, is it worth it?
Testing Strategy 
Customers in Production 
Manual QA by Team 
Unit Tests 
Integration tests 
Automated UI Tests
Manual Testing 
Low initial cost 
Need to acceptance test every feature at least once 
Never can be completely eliminated 
Does not scale with complexity 
Extremely expensive long term
QA Options 
Helps make manual testing 
cheaper & more effective 
Network connectivity 
Environment 
Mock Data
QA Specs 
Look at Gherkin / Cucumber for examples 
Helps to make tests more repeatable 
Can use to outsource testing to other firms 
Painful & expensive
Automated UI Testing 
Appium / UIAutomator type tests 
Usually leveraging the accessibility IDs 
Expensive, flakey 
Can be layered onto most apps after the fact
Functional Testing 
Most Android ‘unit testing’ examples are functional 
Robolectric & InstrumentationTests 
Generally scoped to an Activity / Fragment / Service 
Time consuming to run and nearly as flakey as UI tests 
Useful but should be minimized
Functional Testing Challenges 
Generic Problems 
Asynchronous 
Network based 
! 
! 
Android Specific 
Lifecycle 
Context 
Platform singletons
Functional Test in Theory 
insertMockDataIntoPreferences(conditions) 
waitForActivityAndFragmentToInitialize() 
waitForDataToLoad() 
label = findViewById() 
assertEquals(conditions, label.getText()); 
Preconditions 
Boilerplate 
Actual Test 
testWindSpeedLabel_MetricSystem
Functional Test in Practice
Pitfalls for a Functional Test 
Is the user logged in? 
Wait for Activity, Fragment lifecycle to load screen 
Wait for network call to finish 
Wait for data to load from DB 
Find the TextView 
Finally, check the TextView’s content & color
Unit Testing 
Narrow in scope, each test is 1 case for 1 method 
Do not test Android platform, therefore run quickly 
Cheap to write if architecture is designed for testing 
Flexible for refactoring 
Should be 80% of your tests
Unit Test in Theory 
testWindSpeedLabel_MetricSystem 
given(conditions) 
assertEquals(conditions, label.getText());
Unit Tests in Practice
So why is this so hard?
Activity Fragment Adapter 
ForecastActivity ForecastFragment ForecastAdapter ForecastModel
Keep Android At Arm’s 
Length
Strategies 
Covered 
Dealing with K/V Store 
ViewModels, Presenters, Custom Views 
Not Covered 
Testing network calls 
Testing SQLite / ContentProviders / ORMs
Weather Buoy 
Master list of buoys 
Detail screen with wind 
& wave forecast 
Setting to choose units 
github.com/krschultz/AndroidWeatherBuoyDemo
Tools 
Examples uses only 
Android standard JUnit & InstrumentationTests 
Mockito 
AssertJ 
Better tools exist 
Espresso 
Robolectric 
Dagger
SharedPreferences
How do you catch this?
How do you catch this?
Wrapping Preferences
Testing Preferences Wrapper
Using wrapped Preferences
Using mock Preferences
Wrapping Shared Preferences 
+ Only 1 place to test interaction w/ SharedPreferences 
+ Handle versioning 
+ Keys don’t leak out 
+ Can now mock SharedPreferences w/o Context 
- More code
UI Unit Testing Strategies
Custom Views
Optional TextView 
What happens when we refactor the layout? 
How do we know this feature doesn’t break?
Optional TextView
Testing Optional TextView
Instrument View 
Label 
Value & Units
Custom View 
+ Clean API 
+ Reusable view logic 
- Compose-ability issues
ViewModels
SharedPreferences 
ForecastFragment 
Views 
WaveForecast 
Views 
Views 
WindForecast 
Preferences 
API Client
View Models 
Add presentation logic to underlying models 
Combine multiple models 
Do not have a concept of Activity/Fragment lifecycle 
Do not have a reference to View
Using a ViewModel 
Fragment is responsible for loading models, 
networking, finding views, threading 
ViewModel is responsible for business logic 
Fragment should fail in all cases
“Presentation” Logic 
Colors, visibility 
Interaction between multiple views 
Formatting / humanizing properties 
i18n
Combining Models 
WaveForecast WindForecast Preferences 
BuoyDetailViewModel
SharedPreferences 
Preferences 
API Client 
ForecastFragment WaveForecast 
Views 
Views 
Views 
WindForecast 
ViewModel
ViewModel Creation 
No reference to view at all 
All models can be immutable
Using a ViewModel 
Create view model at the end of network call or DB fetch 
Pass Views to ViewModel for updating
Logic in a ViewModel
Pitfalls 
Creating a ViewModel getter for every view property 
Keeping references to views in the ViewModel
Testing
Use Cases 
Great for screens displaying detail about an object 
Not ideal for collections of items, but Adapters can be 
tested similarly 
Not a great fit for screens with many interactions
Presenters
Presenters 
Same general idea as ViewModel, but includes 
reference to View 
Requires coordinating with Activity/Fragment lifecycle 
Potential for Context leaks if not handled correctly 
More full featured, can take ownership of fetching data, 
threading, network calls, etc
Preferences 
ForecastFragment WaveForecast 
Views 
Views 
Views 
WindForecast 
Presenter 
View Interface
Fragment
Presenter
Fragment Continued 
User interactions delegated to presenter 
Can test using the same methods on the presenter
Presenter Continued 
All business logic belongs in presenter 
Calls back to view for update, remember the view may 
be gone
Use Cases 
Can handle state changes caused by user interaction 
very well 
Really should use Espresso / InstrumentationTests to 
ensure that click handlers call appropriate methods in 
presenter
Summary 
You are building a system, not just an app 
Cost of testing over long term becomes extremely expensive 
Find ways to keep the platform at arms length 
Consider how to test each component from the start
Further Reading 
martinfowler.com/eaaDev/uiArchs.html 
www.objc.io/issue-13/viper.html
Contact 
@kevinrschultz 
github.com/krschultz/AndroidWeatherBuoyDemo 
kevinrschultz.com
Questions?
Backup
Law of Demeter w/ Context
Image Attribution 
! 
Tent - 
House - https://www.flickr.com/photos/18702768@N04/2294709357 
Cake - https://www.flickr.com/photos/personalcreations/14888675499
Long Term Cost 
70 
52.5 
35 
17.5 
0 
Manual Unit Tests UI Tests Test Fixtures 
1 2 3 4 5 6
Stage 1 -> No desire for tests 
Stage 2 -> Desire tests, but can’t build the test 
suite 
Stage 3 -> Have a test suite 
Stage 4 -> Nirvana. Bugs find themselves.
But I Don’t Have Business 
Logic! 
“It’s just simple data in the UI!” 
Not for long (PDP examples) 
Creating a place for the tests to go from the start 
makes it easy to add them (UUID example) 
Every single thing is small, but the sum of testing them 
all is expensive

More Related Content

PDF
Myth vs Reality: Understanding AI/ML for QA Automation - w/ Jonathan Lipps
Applitools
 
PDF
Discover the power of QA automation testing
Softweb Solutions
 
PPTX
Android testing
Bitbar
 
PDF
Agile Testing Pasadena JUG Aug2009
Grig Gheorghiu
 
PPTX
Automated testing web application
Kiattikhun Prathumma
 
PPT
Automated Testing vs Manual Testing
didev
 
PDF
When you get lost in api testing #ForumPHP
Paula Čučuk
 
PPTX
Android testing
JinaTm
 
Myth vs Reality: Understanding AI/ML for QA Automation - w/ Jonathan Lipps
Applitools
 
Discover the power of QA automation testing
Softweb Solutions
 
Android testing
Bitbar
 
Agile Testing Pasadena JUG Aug2009
Grig Gheorghiu
 
Automated testing web application
Kiattikhun Prathumma
 
Automated Testing vs Manual Testing
didev
 
When you get lost in api testing #ForumPHP
Paula Čučuk
 
Android testing
JinaTm
 

What's hot (20)

PDF
Diffy : Automatic Testing of Microservices @ Twitter
Puneet Khanduri
 
ODP
FluentSelenium Presentation Code Camp09
Pyxis Technologies
 
PPT
Test Driven Development - Overview and Adoption
Pyxis Technologies
 
PPT
Automation testing strategy, approach & planning
SivaprasanthRentala1975
 
PDF
An introduction to unit testing
Adam Stephensen
 
PDF
Implementing Test Automation in Agile Projects
Dominik Dary
 
PDF
Android Automation Using Robotium
Mindfire Solutions
 
PDF
Introducing Keyword-Driven Test Automation
TechWell
 
PDF
Testing on Android
Ari Lacenski
 
PPT
Test automation process
Bharathi Krishnamurthi
 
PDF
Testing Experience - Evolution of Test Automation Frameworks
Łukasz Morawski
 
PDF
Introducing Keyword-driven Test Automation
TechWell
 
PDF
ESLint Plugin for UI Tests
Applitools
 
PPTX
Testing for Android: When, Where, and How to Successfully Use Test Automation
Trent Peterson
 
PDF
Test Automation and Keyword-driven testing af Brian Nielsen, CISS/AAU
InfinIT - Innovationsnetværket for it
 
PPT
Automation testing
Biswajit Pratihari
 
PPT
Test Automation On Android Platform Using Robotium
IndicThreads
 
PDF
Engaging IV&V Testing Services for Agile Projects
Ravi Kumar
 
PPTX
Test Automation Techniques for Windows Applications
Tabăra de Testare
 
PPT
Unit testing
dubbu
 
Diffy : Automatic Testing of Microservices @ Twitter
Puneet Khanduri
 
FluentSelenium Presentation Code Camp09
Pyxis Technologies
 
Test Driven Development - Overview and Adoption
Pyxis Technologies
 
Automation testing strategy, approach & planning
SivaprasanthRentala1975
 
An introduction to unit testing
Adam Stephensen
 
Implementing Test Automation in Agile Projects
Dominik Dary
 
Android Automation Using Robotium
Mindfire Solutions
 
Introducing Keyword-Driven Test Automation
TechWell
 
Testing on Android
Ari Lacenski
 
Test automation process
Bharathi Krishnamurthi
 
Testing Experience - Evolution of Test Automation Frameworks
Łukasz Morawski
 
Introducing Keyword-driven Test Automation
TechWell
 
ESLint Plugin for UI Tests
Applitools
 
Testing for Android: When, Where, and How to Successfully Use Test Automation
Trent Peterson
 
Test Automation and Keyword-driven testing af Brian Nielsen, CISS/AAU
InfinIT - Innovationsnetværket for it
 
Automation testing
Biswajit Pratihari
 
Test Automation On Android Platform Using Robotium
IndicThreads
 
Engaging IV&V Testing Services for Agile Projects
Ravi Kumar
 
Test Automation Techniques for Windows Applications
Tabăra de Testare
 
Unit testing
dubbu
 
Ad

Similar to Building Maintainable Android Apps (DroidCon NYC 2014) (20)

PDF
Oh so you test? - A guide to testing on Android from Unit to Mutation
Paul Blundell
 
PPTX
Xamarin Test Cloud - from zero to hero in automated ui testing
Geert van der Cruijsen
 
PDF
Justin Ison
CodeFest
 
PDF
Innovation Generation - The Mobile Meetup: Android Best Practices
Solstice Mobile Argentina
 
PDF
Agile Mobile Testing Workshop
Naresh Jain
 
PDF
How not to suck at unit tests
Benjamin Bishop
 
PPTX
mobile development with androiddfdgdfhdgfdhf.pptx
NgLQun
 
PPTX
Testing the UI of Mobile Applications
Marco Torchiano
 
PDF
Automated Exploratory Testing
Justin Ison
 
PPTX
PPT from Geekle QA Global Summit 2023 conference
SUPARNA KHAMARU
 
PDF
New Android Project: The Most Important Decisions - Vasiliy Zukanov
DroidConTLV
 
PDF
Infinum Android Talks #13 - Developing Android Apps Like Navy Seals by Ivan Kušt
Infinum
 
PDF
Droidcon Spain 2016 - The Pragmatic Android Programmer: from hype to reality
Daniel Gallego Vico
 
PDF
Android-centric-architecture vs. unit testable apps
Paul Wein
 
PDF
Building robust apps
Charles Neveu
 
PPTX
Testing mobile apps
QuickBird Studios GmbH
 
PDF
Continuous, Evolutionary and Large-Scale: A New Perspective for Automated Mob...
Kevin Moran
 
PPTX
Xam expertday
Codrina Merigo
 
PDF
Expedia 3x3 presentation
Drew Hannay
 
PDF
Android Building, Testing and reversing
Enrique López Mañas
 
Oh so you test? - A guide to testing on Android from Unit to Mutation
Paul Blundell
 
Xamarin Test Cloud - from zero to hero in automated ui testing
Geert van der Cruijsen
 
Justin Ison
CodeFest
 
Innovation Generation - The Mobile Meetup: Android Best Practices
Solstice Mobile Argentina
 
Agile Mobile Testing Workshop
Naresh Jain
 
How not to suck at unit tests
Benjamin Bishop
 
mobile development with androiddfdgdfhdgfdhf.pptx
NgLQun
 
Testing the UI of Mobile Applications
Marco Torchiano
 
Automated Exploratory Testing
Justin Ison
 
PPT from Geekle QA Global Summit 2023 conference
SUPARNA KHAMARU
 
New Android Project: The Most Important Decisions - Vasiliy Zukanov
DroidConTLV
 
Infinum Android Talks #13 - Developing Android Apps Like Navy Seals by Ivan Kušt
Infinum
 
Droidcon Spain 2016 - The Pragmatic Android Programmer: from hype to reality
Daniel Gallego Vico
 
Android-centric-architecture vs. unit testable apps
Paul Wein
 
Building robust apps
Charles Neveu
 
Testing mobile apps
QuickBird Studios GmbH
 
Continuous, Evolutionary and Large-Scale: A New Perspective for Automated Mob...
Kevin Moran
 
Xam expertday
Codrina Merigo
 
Expedia 3x3 presentation
Drew Hannay
 
Android Building, Testing and reversing
Enrique López Mañas
 
Ad

Recently uploaded (20)

PDF
vAdobe Premiere Pro 2025 (v25.2.3.004) Crack Pre-Activated Latest
imang66g
 
PPTX
Presentation about Database and Database Administrator
abhishekchauhan86963
 
PPTX
GALILEO CRS SYSTEM | GALILEO TRAVEL SOFTWARE
philipnathen82
 
PDF
What to consider before purchasing Microsoft 365 Business Premium_PDF.pdf
Q-Advise
 
PDF
Enhancing Healthcare RPM Platforms with Contextual AI Integration
Cadabra Studio
 
PPT
Why Reliable Server Maintenance Service in New York is Crucial for Your Business
Sam Vohra
 
PDF
Using licensed Data Loss Prevention (DLP) as a strategic proactive data secur...
Q-Advise
 
PPTX
Can You Build Dashboards Using Open Source Visualization Tool.pptx
Varsha Nayak
 
PDF
advancepresentationskillshdhdhhdhdhdhhfhf
jasmenrojas249
 
PDF
49784907924775488180_LRN2959_Data_Pump_23ai.pdf
Abilash868456
 
PPTX
Explanation about Structures in C language.pptx
Veeral Rathod
 
DOCX
Can You Build Dashboards Using Open Source Visualization Tool.docx
Varsha Nayak
 
PDF
An Experience-Based Look at AI Lead Generation Pricing, Features & B2B Results
Thomas albart
 
PDF
On Software Engineers' Productivity - Beyond Misleading Metrics
Romén Rodríguez-Gil
 
PDF
Adobe Illustrator Crack Full Download (Latest Version 2025) Pre-Activated
imang66g
 
PDF
New Download FL Studio Crack Full Version [Latest 2025]
imang66g
 
PPTX
Maximizing Revenue with Marketo Measure: A Deep Dive into Multi-Touch Attribu...
bbedford2
 
PPTX
Odoo Integration Services by Candidroot Solutions
CandidRoot Solutions Private Limited
 
PDF
Immersive experiences: what Pharo users do!
ESUG
 
PPTX
ConcordeApp: Engineering Global Impact & Unlocking Billions in Event ROI with AI
chastechaste14
 
vAdobe Premiere Pro 2025 (v25.2.3.004) Crack Pre-Activated Latest
imang66g
 
Presentation about Database and Database Administrator
abhishekchauhan86963
 
GALILEO CRS SYSTEM | GALILEO TRAVEL SOFTWARE
philipnathen82
 
What to consider before purchasing Microsoft 365 Business Premium_PDF.pdf
Q-Advise
 
Enhancing Healthcare RPM Platforms with Contextual AI Integration
Cadabra Studio
 
Why Reliable Server Maintenance Service in New York is Crucial for Your Business
Sam Vohra
 
Using licensed Data Loss Prevention (DLP) as a strategic proactive data secur...
Q-Advise
 
Can You Build Dashboards Using Open Source Visualization Tool.pptx
Varsha Nayak
 
advancepresentationskillshdhdhhdhdhdhhfhf
jasmenrojas249
 
49784907924775488180_LRN2959_Data_Pump_23ai.pdf
Abilash868456
 
Explanation about Structures in C language.pptx
Veeral Rathod
 
Can You Build Dashboards Using Open Source Visualization Tool.docx
Varsha Nayak
 
An Experience-Based Look at AI Lead Generation Pricing, Features & B2B Results
Thomas albart
 
On Software Engineers' Productivity - Beyond Misleading Metrics
Romén Rodríguez-Gil
 
Adobe Illustrator Crack Full Download (Latest Version 2025) Pre-Activated
imang66g
 
New Download FL Studio Crack Full Version [Latest 2025]
imang66g
 
Maximizing Revenue with Marketo Measure: A Deep Dive into Multi-Touch Attribu...
bbedford2
 
Odoo Integration Services by Candidroot Solutions
CandidRoot Solutions Private Limited
 
Immersive experiences: what Pharo users do!
ESUG
 
ConcordeApp: Engineering Global Impact & Unlocking Billions in Event ROI with AI
chastechaste14
 

Building Maintainable Android Apps (DroidCon NYC 2014)

  • 1. Building Maintainable Android Applications ! Kevin Schultz (@kevinrschultz) DroidCon NYC 2014 ! kevinrschultz.com github.com/krschultz/AndroidWeatherBuoyDemo
  • 4. Treading Water Time spent on features dwindles Infrequent releases due to high QA costs Heisenbug whack-a-mole Fear of change Infrastructure Bugs Features
  • 5. Drowning Platform Changes Business Pivot Competitors Panic How many regressions will you cause when implementing Material Design?
  • 7. The codebase is a mess!
  • 8. Unlikely to be better next time Clean code is necessary but insufficient for maintainability We are state of the art today, what about next year? Why do Android apps always seem to become unmaintainable?
  • 9. Android was initially for Apps Documentation & samples are small scale Old build system was deficient Testing tools are still sub-par Framework was not designed for testability Performance trumped clean code
  • 10. You must build a system to counter software entropy
  • 11. Software Entropy “As a system is modified, its disorder, or entropy, always increases. This is known as software entropy.” - Ivar Jacobson “Legacy code is code without tests” - Michael Feathers
  • 12. System Espresso Functional Tests UI Tests Build Unit Tests App CI Server
  • 13. System Thinking How will each component be tested over its lifetime? What leads to the minimum cost of development including QA time? If a library makes it easy to add a feature but harder to test, is it worth it? If a tool breaks CI, is it worth it?
  • 14. Testing Strategy Customers in Production Manual QA by Team Unit Tests Integration tests Automated UI Tests
  • 15. Manual Testing Low initial cost Need to acceptance test every feature at least once Never can be completely eliminated Does not scale with complexity Extremely expensive long term
  • 16. QA Options Helps make manual testing cheaper & more effective Network connectivity Environment Mock Data
  • 17. QA Specs Look at Gherkin / Cucumber for examples Helps to make tests more repeatable Can use to outsource testing to other firms Painful & expensive
  • 18. Automated UI Testing Appium / UIAutomator type tests Usually leveraging the accessibility IDs Expensive, flakey Can be layered onto most apps after the fact
  • 19. Functional Testing Most Android ‘unit testing’ examples are functional Robolectric & InstrumentationTests Generally scoped to an Activity / Fragment / Service Time consuming to run and nearly as flakey as UI tests Useful but should be minimized
  • 20. Functional Testing Challenges Generic Problems Asynchronous Network based ! ! Android Specific Lifecycle Context Platform singletons
  • 21. Functional Test in Theory insertMockDataIntoPreferences(conditions) waitForActivityAndFragmentToInitialize() waitForDataToLoad() label = findViewById() assertEquals(conditions, label.getText()); Preconditions Boilerplate Actual Test testWindSpeedLabel_MetricSystem
  • 22. Functional Test in Practice
  • 23. Pitfalls for a Functional Test Is the user logged in? Wait for Activity, Fragment lifecycle to load screen Wait for network call to finish Wait for data to load from DB Find the TextView Finally, check the TextView’s content & color
  • 24. Unit Testing Narrow in scope, each test is 1 case for 1 method Do not test Android platform, therefore run quickly Cheap to write if architecture is designed for testing Flexible for refactoring Should be 80% of your tests
  • 25. Unit Test in Theory testWindSpeedLabel_MetricSystem given(conditions) assertEquals(conditions, label.getText());
  • 26. Unit Tests in Practice
  • 27. So why is this so hard?
  • 28. Activity Fragment Adapter ForecastActivity ForecastFragment ForecastAdapter ForecastModel
  • 29. Keep Android At Arm’s Length
  • 30. Strategies Covered Dealing with K/V Store ViewModels, Presenters, Custom Views Not Covered Testing network calls Testing SQLite / ContentProviders / ORMs
  • 31. Weather Buoy Master list of buoys Detail screen with wind & wave forecast Setting to choose units github.com/krschultz/AndroidWeatherBuoyDemo
  • 32. Tools Examples uses only Android standard JUnit & InstrumentationTests Mockito AssertJ Better tools exist Espresso Robolectric Dagger
  • 34. How do you catch this?
  • 35. How do you catch this?
  • 40. Wrapping Shared Preferences + Only 1 place to test interaction w/ SharedPreferences + Handle versioning + Keys don’t leak out + Can now mock SharedPreferences w/o Context - More code
  • 41. UI Unit Testing Strategies
  • 43. Optional TextView What happens when we refactor the layout? How do we know this feature doesn’t break?
  • 46. Instrument View Label Value & Units
  • 47. Custom View + Clean API + Reusable view logic - Compose-ability issues
  • 49. SharedPreferences ForecastFragment Views WaveForecast Views Views WindForecast Preferences API Client
  • 50. View Models Add presentation logic to underlying models Combine multiple models Do not have a concept of Activity/Fragment lifecycle Do not have a reference to View
  • 51. Using a ViewModel Fragment is responsible for loading models, networking, finding views, threading ViewModel is responsible for business logic Fragment should fail in all cases
  • 52. “Presentation” Logic Colors, visibility Interaction between multiple views Formatting / humanizing properties i18n
  • 53. Combining Models WaveForecast WindForecast Preferences BuoyDetailViewModel
  • 54. SharedPreferences Preferences API Client ForecastFragment WaveForecast Views Views Views WindForecast ViewModel
  • 55. ViewModel Creation No reference to view at all All models can be immutable
  • 56. Using a ViewModel Create view model at the end of network call or DB fetch Pass Views to ViewModel for updating
  • 57. Logic in a ViewModel
  • 58. Pitfalls Creating a ViewModel getter for every view property Keeping references to views in the ViewModel
  • 60. Use Cases Great for screens displaying detail about an object Not ideal for collections of items, but Adapters can be tested similarly Not a great fit for screens with many interactions
  • 62. Presenters Same general idea as ViewModel, but includes reference to View Requires coordinating with Activity/Fragment lifecycle Potential for Context leaks if not handled correctly More full featured, can take ownership of fetching data, threading, network calls, etc
  • 63. Preferences ForecastFragment WaveForecast Views Views Views WindForecast Presenter View Interface
  • 66. Fragment Continued User interactions delegated to presenter Can test using the same methods on the presenter
  • 67. Presenter Continued All business logic belongs in presenter Calls back to view for update, remember the view may be gone
  • 68. Use Cases Can handle state changes caused by user interaction very well Really should use Espresso / InstrumentationTests to ensure that click handlers call appropriate methods in presenter
  • 69. Summary You are building a system, not just an app Cost of testing over long term becomes extremely expensive Find ways to keep the platform at arms length Consider how to test each component from the start
  • 70. Further Reading martinfowler.com/eaaDev/uiArchs.html www.objc.io/issue-13/viper.html
  • 74. Law of Demeter w/ Context
  • 75. Image Attribution ! Tent - House - https://www.flickr.com/photos/18702768@N04/2294709357 Cake - https://www.flickr.com/photos/personalcreations/14888675499
  • 76. Long Term Cost 70 52.5 35 17.5 0 Manual Unit Tests UI Tests Test Fixtures 1 2 3 4 5 6
  • 77. Stage 1 -> No desire for tests Stage 2 -> Desire tests, but can’t build the test suite Stage 3 -> Have a test suite Stage 4 -> Nirvana. Bugs find themselves.
  • 78. But I Don’t Have Business Logic! “It’s just simple data in the UI!” Not for long (PDP examples) Creating a place for the tests to go from the start makes it easy to add them (UUID example) Every single thing is small, but the sum of testing them all is expensive