Upgrade to Pro
— share decks privately, control downloads, hide ads and more …
Speaker Deck
Sign up for free
Menu
Search
Features
All features
Private URLs
Password Protection
Custom URLS
Scheduled publishing
Remove Branding
Restrict embedding
Deck Collections
Notes
Features
All features
Private URLs
Password Protection
Custom URLS
Scheduled publishing
Remove Branding
Restrict embedding
Deck Collections
Notes
Explore
Featured decks
Featured speakers
Programming
Technology
Storyboards
Explore
Featured decks
Featured speakers
Programming
Technology
Storyboards
Pricing
Search
Sign in
Sign up for free
MCE2015 - Automated Testing for Modern Android ...
Search
Andy Dyer
February 06, 2015
Programming
1.5k
0
Share
Embed
Copy iframe code
Copy JS code
Copy link
Start on current slide
MCE2015 - Automated Testing for Modern Android Applications
Andy Dyer
February 06, 2015
More Decks by Andy Dyer
See All by Andy Dyer
AppCraft: Faster Than a Speeding Release Train
abdyer
1
380
Multiple Developers, One App: How to Not Break Everything
abdyer
0
390
Things That Suck About Android Development
abdyer
0
620
Building an Android Wear app
abdyer
0
110
BABBQ5 - Automated Testing for Modern Android Applications
abdyer
14
3.8k
Other Decks in Programming
See All in Programming
半永久的に提供し続けられるプライベートクラウドを目指して ― 利用者の認知負荷を抑えるAPI抽象化とハードウェア世代交代の基盤設計
tomokon
0
120
Augmenting AI with the Power of Jakarta EE
ivargrimstad
0
370
Streamlitで実現する自然言語データアプリ開発
ayumu_yamaguchi
1
320
Augmenting AI with the Power of Jakarta EE
ivargrimstad
0
310
Verilogで学ぶCPU自作入門.pdf
uyuki234
8
3.6k
海上で動くGoサーバー: goroutineとchannelでさばく航行データストリーム
atsuki_seo
0
960
C#の現在地 進化の歴史と、AI時代の.NET Everywhere
neuecc
4
4.1k
setup-vp GitLab対応の裏側
naokihaba
0
130
【高い買い物LT会】初任給で話題の国産フィジカルAIを買った話
akagami
PRO
0
170
JRuby: Past, Present, and Future
headius
0
210
Turning Architecture into Unit Tests in the AI Era (NSSpain XIV)
steliosf
PRO
1
100
JAWS-UG 東京支部が始める、JAWS-UG支部コラボ / JAWS-UG lunchtime LT Collaboration
y0hgi
0
160
Featured
See All Featured
Jess Joyce - The Pitfalls of Following Frameworks
techseoconnect
PRO
1
420
What’s in a name? Adding method to the madness
productmarketing
PRO
24
4.2k
Being A Developer After 40
akosma
91
590k
So, you think you're a good person
axbom
PRO
2
2.2k
Conquering PDFs: document understanding beyond plain text
inesmontani
PRO
4
3.1k
State of Search Keynote: SEO is Dead Long Live SEO
ryanjones
0
290
Ecommerce SEO: The Keys for Success Now & Beyond - #SERPConf2024
aleyda
1
2.2k
Applied NLP in the Age of Generative AI
inesmontani
PRO
4
2.5k
VelocityConf: Rendering Performance Case Studies
addyosmani
331
25k
エンジニアに許された特別な時間の終わり
watany
109
250k
Marketing to machines
jonoalderson
1
5.8k
The Curse of the Amulet
leimatthew05
3
15k
Transcript
Automated Testing for Modern Android Applications
Andy Dyer +AndrewDyer @dammitandy
None
Making Android apps testable
Dynamic languages Tests shouldn't drive implementation.
Static languages You know nothing.
Making Android apps testable 1. Dependency injection 2. Mocking &
stubbing 3. Unit & integration tests
Dependency injection
Dependency injection • Classes receive dependencies, don’t have to know
where to find them or how to create them • Swap components for mocks in tests • Use different components for different build flavors, etc.
Basic dependency injection public class Beer implements Reinheitsgebot { Water
water; Barley barley; Hops hops; public Beer(Water water, Barley barley, Hops hops) { this.water = water; this.barley = barley; this.hops = hops; } }
Dagger A Java dependency injection library
Dagger • Defining dependencies at compile time avoids reflection at
runtime • Compiler validates components, modules, and injections • Dagger 2 is currently in alpha, but already being used by Google in production apps google.github.io/dagger/
Dagger Modules @Module public class MyModule { @Provides @Singleton public
MyService provideMyService() { return new MyService(); } }
Dagger Components @Component(modules = MyModule.class) public interface Graph { void
inject(Activity activity); void inject(Fragment fragment); public final static class Initializer { public static Graph init(boolean mockMode) { return Dagger_Graph.builder().build(); } } }
Dagger Object Graph public class MyApplication extends Application { @Getter
static DemoApplication instance; @Getter Graph graph; @Override public void onCreate() { super.onCreate(); instance = this; graph = Graph.Initializer.init(false); } public void setMockMode(boolean useMock) { graph = Graph.Initializer.init(useMock); } }
Dagger dependency injection public class MyFragment extends Fragment { @Inject
MyService service; @Override public void onViewCreated(View view, Bundle savedInstanceState) { MyApplication.getInstance().getGraph().inject(this); service.getMyData(); } }
Learning more about Dagger • Jake Wharton - Dependency Injection
with Dagger 2 parleys.com/play/5471cdd1e4b065ebcfa1d557 • Gregory Kick - Dagger 2: A New Type of Dependency Injection youtube.com/watch?v=oK_XtfXPkqw
Mocking & Stubbing
Mocking & Stubbing • Substitute runtime implementation for something that
can be predictably tested in isolation • Verify behavior
A Java mocking library
Mockito • Mock/stub dependencies and function return values • Inject
mocks to validate behavior in tests • Use included Hamcrest matchers for clear, readable tests code.google.com/p/mockito/
Using Mockito // create mock MyClass mocked = mock(MyClass.class); //
specify behavior when(mocked.doSomething()).thenReturn(somethingElse); // verify method calls verify(mocked).getMyData(anyInt(), anyString());
Using Mockito // capture arguments ArgumentCaptor<Callback> captor = ArgumentCaptor.forClass(Callback.class); verify(authenticationService).login(anyString(),
anyString(), captor.capture()); // simulate error conditions, etc. captor.getValue().failure(RetrofitError.unexpectedError( "Invalid password", new Exception()));
Unit & Integration Tests
Tests or it didn't happen
Unit testing public class BeerTest extends InstrumentationTestCase { @Inject Beer
beer; @Override protected void setUp() throws Exception { MyApplication.getInstance().getGraph().inject(this); } public void testBeerIsGood() { assertTrue(beer.isGood()); } }
An Android UI testing library
Espresso • Handles activity creation & state sync • Simple,
concise API • Really fast! code.google.com/p/android-test-kit*
UI testing with Espresso public class MyActivityTest extends ActivityInstrumentationTestCase2<MyActivity> {
public MyActivityTest() { super(MyActivity.class); } @Override protected void setUp() throws Exception { super.setUp(); getActivity(); // trigger activity launch } public void testInvalidEmailShowsError() { onView(withId(R.id.email)).perform(typeText("abc"), closeSoftKeyboard()); onView(withId(R.id.email_sign_in_button)).perform(click()); onView(withId(R.id.email)).check(matches(withError( getActivity().getString(R.string.error_invalid_email)))); } }
Sample application • Dagger object graph • Retrofit API with
sample request • Lombok & Android Studio plugin • Login activity • Activity with fragment to make API request and display data
Testing the login activity • Simulate data entry and taps
to validate UI functionality • Simulate an error without making a network request
Testing the main activity • Verify the RecyclerView contains data
• Simulate taps to validate the appropriate URLs are loaded in a WebView
Testing the API • Use mock API response loaded from
text file to validate JSON parsing
Demo
Known issues • Some tests may fail on older devices/emulators
such as those running < API 18. Hopefully this will be fixed soon by an update to the test support library.
Additional resources • Bryan Stern/Circle Engineering - Instrumentation Testing with
Dagger, Mockito, and Espresso engineering.circle.com/instrumentation-testing-with-dagger- mockito-and-espresso
Conclusion Using dependency injection, mocking, and automated testing tools helps
us build better apps. Working together as a community, we can make testing even easier.
Questions?
Slides speakerdeck.com/abdyer/mce2015-automated-testing-for- modern-android-applications Code github.com/abdyer/android-test-demo/releases/tag/ mceconf-2015 +AndrewDyer @dammitandy