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
390
Multiple Developers, One App: How to Not Break Everything
abdyer
0
400
Things That Suck About Android Development
abdyer
0
630
Building an Android Wear app
abdyer
0
110
BABBQ5 - Automated Testing for Modern Android Applications
abdyer
14
3.9k
Other Decks in Programming
See All in Programming
AmebaブログはKMPから卒業します
kmars0605
0
320
プロジェクトコードをキレイキレイしよう!暗黙的な参照を読み解く静的解析
ostk0069
0
200
SFCで実現する病院・医療システムの動的組み立て式UI
koukimiura
1
170
조합이폭발하는디자인시스템이걸눈으로도테스트하라고요
giljongyu
0
720
Spec-driven Development with AI
simas
PRO
0
2.2k
AIがコードを書いてくれる時代、我々は何を確かめるのか
yosuke_furukawa
PRO
13
5.7k
ActionController meets Protocol Buffers
sorah
1
780
Goコンパイラを作ってGoをもっと理解する / Build a Go compiler to better understand Go
ikura_hamu
0
120
Enforcing Your Architecture with Unit Tests in the AI Era (Swift Connection X)
steliosf
PRO
1
130
Event is what happens
moro
2
3.6k
クラウドエージェントは、 何がそんなに便利なのか / what makes cloud agents so useful
rkaga
5
770
TS 7.0 で baseUrl が使えなくなった今、パスエイリアスをどうするか
bicstone
2
500
Featured
See All Featured
Understanding Cognitive Biases in Performance Measurement
bluesmoon
32
3.1k
コードの90%をAIが書く世界で何が待っているのか / What awaits us in a world where 90% of the code is written by AI
rkaga
63
47k
Building AI with AI
inesmontani
PRO
1
1.4k
HU Berlin: Industrial-Strength Natural Language Processing with spaCy and Prodigy
inesmontani
PRO
0
800
Ethics towards AI in product and experience design
skipperchong
2
460
Future Trends and Review - Lecture 12 - Web Technologies (1019888BNR)
signer
PRO
0
3.8k
How to Ace a Technical Interview
jacobian
280
24k
Responsive Adventures: Dirty Tricks From The Dark Corners of Front-End
smashingmag
254
23k
How Fast Is Fast Enough? [PerfNow 2025]
tammyeverts
3
970
Fight the Zombie Pattern Library - RWD Summit 2016
marcelosomers
234
18k
Leadership Guide Workshop - DevTernity 2021
reverentgeek
1
420
Principles of Awesome APIs and How to Build Them.
keavy
128
18k
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