SlideShare ist ein Scribd-Unternehmen logo
1 von 33
Automated testing
Android
Dependency Injection and Dagger
Dependency Injection
Dagger
Live Coding Sample 1
Live Coding Sample 2
The Business Goal
Why not automated tests on mobile?
Motivation for Dependency Injection
● Decouple concrete from concrete
● Uniformity
● Reduced Dependency Carrying
● More Testable Code
Decouple concrete from Concrete
class MyStringUtils {
private Context context;
StringUtils(Context context) {
this.context = context;
}
public String helloWorld() {
return context.getString(R.string.hello_ciklum);
}
}
Decouple concrete from Concrete
class MainActivity extends Activity implements View.OnClickListener {
@Inject MyStringUtils myStringUtils;
void onCreate(Bundle savedInstanceState) {
… }
void onClick(View v) {
MyStringUtils myStringUtils1 = new MyStringUtils(this.getApplication()); // new operator
MyStringUtils myStringUtils2 = MyStringUtils.getInstance(this); // singleton pattern
MyStringUtils myStringUtils3 = MyStringUtilsFactory.getInstance(this); // factory patterns
String str1 myStr = MyStringUtils.helloWorld(this); // Static
String str = myStringUtils.helloWorld();
TextView msgView = (TextView) findViewById(R.id.textView);
msgView.setText(str);
}}}
Uniformity
class MainActivity extends Activity implements View.OnClickListener {
@Inject MyStringUtils myStringUtils;
void onCreate(Bundle savedInstanceState) {
… }
void onClick(View v) {
MyStringUtils myStringUtils1 = new MyStringUtils(this.getApplication()); // new instance
MyStringUtils myStringUtils2 = MyStringUtils.getInstance(this); // Singleton pattern
MyStringUtils myStringUtils3 = MyStringUtilsFactory.getInstance(this); // Factory pattern
String str1 myStr = MyStringUtils.helloWorld(this); // Static
String str = myStringUtils.helloWorld();
TextView msgView = (TextView) findViewById(R.id.textView);
msgView.setText(str);
}
}}
Dependency Carrying
class MyActivity extends Activity {
onClick(View v) {
A a = new A(this);
a.doSometing();
}
}
class A {
Context mContext;
public (Context mContext){
this.mContext = mContext;
}
public doSomething() {
B b = new B(mContext);
String str =
b.getSomeString(R.strings.helloWorld);
}
}
class B {
Context mContext;
public B(Context mContext) {
this.mContext = mContext;
}
public String getSomeString(int resourceId) {
return
mContext.getString(resourceId);
}
}
Reduced Dependency Carrying
@Module class ProdModule {
Context mContext;
public ProdModule(Context mContext) {
this.mContext = mContext;
}
@Provide B provideB() {
return new B(context);
}
@Provide A provideA(B b) {
return new A(b);
}
}
class MyActivity {
@Inject A a;
onCreate(){
((MyApplication)getApplication()).inject(this);
}
onClick(View v) {
A a = new A(this);
a.doSomething();
}
}
class A {
@Inject B b;
public doSomething() {
String str = b.getSomeString(R.strings.helloWorld);
}
}
class B {
Context mContext;
public B(Context mContext) {
this.mContext = mContext;
}
public String getSomeString(int resourceId) {
return mContext.getString(resourceId);
}
}
More Testable Code
class MainActivity extends Activity implements View.OnClickListener {
@Inject MyStringUtils myStringUtils;
void onCreate(Bundle savedInstanceState) {
… }
void onClick(View v) {
String str = myStringUtils.helloWorld();
TextView msgView = (TextView) findViewById(R.id.textView);
msgView.setText(str);
}
}}
Other advantages
● More Reusable Code
● More Readable Code
● Reduced Dependencies
Dependency Injection
Dagger
Live Coding Sample 1
Live Coding Sample 2
DAGger
Direct
Acyclic
Graph
Coffee maker
public class CoffeMaker {
@Inject Heater heater;
@Inject Pump pump;
public void brew() {
heater.on();
pump.pump();
System.out.println("coffee!");
heater.off();
}
}
class Thermosiphon implements Pump {
Heater heater;
Thermosiphon(Heater heater) {
this.heater = heater;
}
@Override public void pump() {
if (heater.isHot()) {
System.out.println("=> => pumping => =>");
}
}
Declare Dependencies
class Thermosiphon implements Pump {
Heater heater;
@Inject
Thermosiphon(Heater heater) {
this.heater = heater;
}
}
Satisfy Dependencies
@Module
class DripCoffeeModule {
@Provides Heater provideHeater() {
return new ElectricHeater();
}
@Provides Pump providePump(Thermosiphon pump) {
return pump;
}
}
Build the Graph
class CoffeeApp {
public static void main(String[] args) {
ObjectGraph objectGraph = ObjectGraph.create(new
DripCoffeeModule());
CoffeeMaker coffeeMaker = objectGraph.get(CoffeeMaker.class);
coffeeMaker.brew();
} }
Neat features
● Lazy<T>
● Module overrides
Lazy<T>
class GridingCoffeeMaker {
@Inject Lazy<Grinder> lazyGrinder;
public void brew() {
while (needsGrinding()) {
// Grinder created once and cached.
Grinder grinder = lazyGrinder.get()
grinder.grind();
}
} }
Module Overrides
@Module(
includes = DripCoffeeModule.class,
injects = CoffeeMakerTest.class,
overrides = true
)
static class TestModule {
@Provides @Singleton Heater provideHeater() {
return Mockito.mock(Heater.class);
}
}
Dependency Injection
Dagger
Live Coding Sample 1
Live Coding Sample 2
Live coding - Sample 1
● add dependencies (with Gradle)
● create module
● set up Dagger in Application context
● inject dependencies to Activity
● create Activity test which injects a mock
Add depedencies (Gradle)
dependencies {
……...
compile 'com.squareup.dagger:dagger:1.2.1'
compile 'com.squareup.dagger:dagger-compiler:1.2.1'
androidTestCompile 'org.mockito:mockito-core:1.9.5'
androidTestCompile 'com.google.dexmaker:dexmaker:1.0'
androidTestCompile 'com.google.dexmaker:dexmaker-mockito:1.0'
}
Module
@Module(
injects = {
MyStringUtils.class, MainActivity.class })
class ProdModule {
Application application;
ProdModule(Application application){
this.application = application;
}
@Provides @Singleton
MyStringUtils provideMyStringUtils() {
return new MyStringUtils(application);
}
Define Dagger Application
class MyApplication extends Application {
ObjectGraph mGraph;
void onCreate() {
super.onCreate();
mGraph = ObjectGraph.create(getModules().toArray());
}
void inject(Object o){
mGraph.inject(o);
}
List<Object> getModules() {
List<Object> result = new ArrayList<Object>();
result.add(new ProdModule(this));
return result;
}}
Create MyStringUtils
class MyStringUtils {
MyStringUtils(Context context) {
this.context = context;
}
public String helloWorld() {
return context.getString(R.string.hello_ciklum);
}
}
Inject dependencies Activity
class MainActivity extends Activity {
@Inject
MyStringUtils myStringUtils;
void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// set dependencies to this activity
((MyApplication)getApplication()).inject(this);
setContentView(R.layout.activity_main);
findViewById(R.id.button).setOnClickListener(this);
}
Unit test Activity with mock
class MainActivityUnitTest extends ActivityUnitTestCase<MainActivity> {
@Inject
MyStringUtils myStringUtils;
void setUp() {
// create test application context, Dagger Graph with our test module.
MyApplication application = new TestApplication();
application.inject(this); // inject the dependencies we need to this class
setApplication(application); // use our custom test application context
}
void testOnClick() {
String testingStr = "olala";
when(myStringUtils.helloWorld()).thenReturn(testingStr);
this.activity = startActivity(intent, null, null);
// the test
View view = activity.findViewById(R.id.button);
activity.onClick(view);
// verify the mock was invoked
verify(myStringUtils, times(1)).helloWorld();
// assert view got updated correctly
TextView msgView = (TextView) activity.findViewById(R.id.textView);
assertEquals(testingStr, msgView.getText());
}
Dependency Injection
Dagger
Live Coding Sample 1
Live Coding Sample 2
Sample app 2
● Threads
● HTTP mocks
Tips, tricks and Frameworks
● https://github.com/tha022/dagger-testing-example
● https://github.com/fizz-buzz/fb-android-dagger

Weitere ähnliche Inhalte

Was ist angesagt?

A GWT Application with MVP Pattern Deploying to CloudFoundry using Spring Roo
A GWT Application with MVP Pattern Deploying to CloudFoundry using  Spring Roo A GWT Application with MVP Pattern Deploying to CloudFoundry using  Spring Roo
A GWT Application with MVP Pattern Deploying to CloudFoundry using Spring Roo Ali Parmaksiz
 
My way to clean android v2 English DroidCon Spain
My way to clean android v2 English DroidCon SpainMy way to clean android v2 English DroidCon Spain
My way to clean android v2 English DroidCon SpainChristian Panadero
 
The Ring programming language version 1.10 book - Part 82 of 212
The Ring programming language version 1.10 book - Part 82 of 212The Ring programming language version 1.10 book - Part 82 of 212
The Ring programming language version 1.10 book - Part 82 of 212Mahmoud Samir Fayed
 
arataga. SObjectizer and RESTinio in action: a real-world example
arataga. SObjectizer and RESTinio in action: a real-world examplearataga. SObjectizer and RESTinio in action: a real-world example
arataga. SObjectizer and RESTinio in action: a real-world exampleYauheni Akhotnikau
 
Intro to Retrofit 2 and RxJava2
Intro to Retrofit 2 and RxJava2Intro to Retrofit 2 and RxJava2
Intro to Retrofit 2 and RxJava2Fabio Collini
 
Dagger 2. Right way to do Dependency Injection
Dagger 2. Right way to do Dependency InjectionDagger 2. Right way to do Dependency Injection
Dagger 2. Right way to do Dependency InjectionStfalcon Meetups
 
Dagger 2. The Right Way to Dependency Injections
Dagger 2. The Right Way to Dependency InjectionsDagger 2. The Right Way to Dependency Injections
Dagger 2. The Right Way to Dependency InjectionsGlobalLogic Ukraine
 
Selenium my sql and junit user guide
Selenium my sql and junit user guideSelenium my sql and junit user guide
Selenium my sql and junit user guideFahad Shiekh
 
Dive into SObjectizer 5.5. Eighth Part: Dispatchers
Dive into SObjectizer 5.5. Eighth Part: DispatchersDive into SObjectizer 5.5. Eighth Part: Dispatchers
Dive into SObjectizer 5.5. Eighth Part: DispatchersYauheni Akhotnikau
 
Your IDE Deserves Better
Your IDE Deserves BetterYour IDE Deserves Better
Your IDE Deserves BetterBoris Litvinsky
 
Why Kotlin - Apalon Kotlin Sprint Part 1
Why Kotlin - Apalon Kotlin Sprint Part 1Why Kotlin - Apalon Kotlin Sprint Part 1
Why Kotlin - Apalon Kotlin Sprint Part 1Kirill Rozov
 
The Ring programming language version 1.10 book - Part 72 of 212
The Ring programming language version 1.10 book - Part 72 of 212The Ring programming language version 1.10 book - Part 72 of 212
The Ring programming language version 1.10 book - Part 72 of 212Mahmoud Samir Fayed
 
Dive into SObjectizer 5.5. Seventh part: Message Limits
Dive into SObjectizer 5.5. Seventh part: Message LimitsDive into SObjectizer 5.5. Seventh part: Message Limits
Dive into SObjectizer 5.5. Seventh part: Message LimitsYauheni Akhotnikau
 

Was ist angesagt? (20)

A GWT Application with MVP Pattern Deploying to CloudFoundry using Spring Roo
A GWT Application with MVP Pattern Deploying to CloudFoundry using  Spring Roo A GWT Application with MVP Pattern Deploying to CloudFoundry using  Spring Roo
A GWT Application with MVP Pattern Deploying to CloudFoundry using Spring Roo
 
My way to clean android V2
My way to clean android V2My way to clean android V2
My way to clean android V2
 
React hooks
React hooksReact hooks
React hooks
 
Devoxx 2012 (v2)
Devoxx 2012 (v2)Devoxx 2012 (v2)
Devoxx 2012 (v2)
 
Angular2 + rxjs
Angular2 + rxjsAngular2 + rxjs
Angular2 + rxjs
 
My way to clean android v2 English DroidCon Spain
My way to clean android v2 English DroidCon SpainMy way to clean android v2 English DroidCon Spain
My way to clean android v2 English DroidCon Spain
 
The Ring programming language version 1.10 book - Part 82 of 212
The Ring programming language version 1.10 book - Part 82 of 212The Ring programming language version 1.10 book - Part 82 of 212
The Ring programming language version 1.10 book - Part 82 of 212
 
F1
F1F1
F1
 
arataga. SObjectizer and RESTinio in action: a real-world example
arataga. SObjectizer and RESTinio in action: a real-world examplearataga. SObjectizer and RESTinio in action: a real-world example
arataga. SObjectizer and RESTinio in action: a real-world example
 
Android TDD
Android TDDAndroid TDD
Android TDD
 
Intro to Retrofit 2 and RxJava2
Intro to Retrofit 2 and RxJava2Intro to Retrofit 2 and RxJava2
Intro to Retrofit 2 and RxJava2
 
Gwt RPC
Gwt RPCGwt RPC
Gwt RPC
 
Dagger 2. Right way to do Dependency Injection
Dagger 2. Right way to do Dependency InjectionDagger 2. Right way to do Dependency Injection
Dagger 2. Right way to do Dependency Injection
 
Dagger 2. The Right Way to Dependency Injections
Dagger 2. The Right Way to Dependency InjectionsDagger 2. The Right Way to Dependency Injections
Dagger 2. The Right Way to Dependency Injections
 
Selenium my sql and junit user guide
Selenium my sql and junit user guideSelenium my sql and junit user guide
Selenium my sql and junit user guide
 
Dive into SObjectizer 5.5. Eighth Part: Dispatchers
Dive into SObjectizer 5.5. Eighth Part: DispatchersDive into SObjectizer 5.5. Eighth Part: Dispatchers
Dive into SObjectizer 5.5. Eighth Part: Dispatchers
 
Your IDE Deserves Better
Your IDE Deserves BetterYour IDE Deserves Better
Your IDE Deserves Better
 
Why Kotlin - Apalon Kotlin Sprint Part 1
Why Kotlin - Apalon Kotlin Sprint Part 1Why Kotlin - Apalon Kotlin Sprint Part 1
Why Kotlin - Apalon Kotlin Sprint Part 1
 
The Ring programming language version 1.10 book - Part 72 of 212
The Ring programming language version 1.10 book - Part 72 of 212The Ring programming language version 1.10 book - Part 72 of 212
The Ring programming language version 1.10 book - Part 72 of 212
 
Dive into SObjectizer 5.5. Seventh part: Message Limits
Dive into SObjectizer 5.5. Seventh part: Message LimitsDive into SObjectizer 5.5. Seventh part: Message Limits
Dive into SObjectizer 5.5. Seventh part: Message Limits
 

Ähnlich wie Automated Testing on Android with Dagger DI

Overview of Android Infrastructure
Overview of Android InfrastructureOverview of Android Infrastructure
Overview of Android InfrastructureAlexey Buzdin
 
Overview of Android Infrastructure
Overview of Android InfrastructureOverview of Android Infrastructure
Overview of Android InfrastructureC.T.Co
 
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
 
Sharper Better Faster Dagger ‡ - Droidcon SF
Sharper Better Faster Dagger ‡ - Droidcon SFSharper Better Faster Dagger ‡ - Droidcon SF
Sharper Better Faster Dagger ‡ - Droidcon SFPierre-Yves Ricau
 
Workshop 26: React Native - The Native Side
Workshop 26: React Native - The Native SideWorkshop 26: React Native - The Native Side
Workshop 26: React Native - The Native SideVisual Engineering
 
Sword fighting with Dagger GDG-NYC Jan 2016
 Sword fighting with Dagger GDG-NYC Jan 2016 Sword fighting with Dagger GDG-NYC Jan 2016
Sword fighting with Dagger GDG-NYC Jan 2016Mike Nakhimovich
 
Android architecture
Android architecture Android architecture
Android architecture Trong-An Bui
 
Hacking the Codename One Source Code - Part IV.pdf
Hacking the Codename One Source Code - Part IV.pdfHacking the Codename One Source Code - Part IV.pdf
Hacking the Codename One Source Code - Part IV.pdfShaiAlmog1
 
Android testing
Android testingAndroid testing
Android testingSean Tsai
 
Strategy Design Pattern
Strategy Design PatternStrategy Design Pattern
Strategy Design PatternGanesh Kolhe
 
Architecting your GWT applications with GWT-Platform - Lesson 02
Architecting your GWT applications with GWT-Platform - Lesson 02Architecting your GWT applications with GWT-Platform - Lesson 02
Architecting your GWT applications with GWT-Platform - Lesson 02rhemsolutions
 
Diving in the Flex Data Binding Waters
Diving in the Flex Data Binding WatersDiving in the Flex Data Binding Waters
Diving in the Flex Data Binding Watersmichael.labriola
 

Ähnlich wie Automated Testing on Android with Dagger DI (20)

Overview of Android Infrastructure
Overview of Android InfrastructureOverview of Android Infrastructure
Overview of Android Infrastructure
 
Overview of Android Infrastructure
Overview of Android InfrastructureOverview of Android Infrastructure
Overview of Android Infrastructure
 
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
 
Sharper Better Faster Dagger ‡ - Droidcon SF
Sharper Better Faster Dagger ‡ - Droidcon SFSharper Better Faster Dagger ‡ - Droidcon SF
Sharper Better Faster Dagger ‡ - Droidcon SF
 
Workshop 26: React Native - The Native Side
Workshop 26: React Native - The Native SideWorkshop 26: React Native - The Native Side
Workshop 26: React Native - The Native Side
 
Sword fighting with Dagger GDG-NYC Jan 2016
 Sword fighting with Dagger GDG-NYC Jan 2016 Sword fighting with Dagger GDG-NYC Jan 2016
Sword fighting with Dagger GDG-NYC Jan 2016
 
Guice2.0
Guice2.0Guice2.0
Guice2.0
 
Hilt Annotations
Hilt AnnotationsHilt Annotations
Hilt Annotations
 
Design Patterns
Design PatternsDesign Patterns
Design Patterns
 
Android architecture
Android architecture Android architecture
Android architecture
 
Hacking the Codename One Source Code - Part IV.pdf
Hacking the Codename One Source Code - Part IV.pdfHacking the Codename One Source Code - Part IV.pdf
Hacking the Codename One Source Code - Part IV.pdf
 
Android testing
Android testingAndroid testing
Android testing
 
Strategy Design Pattern
Strategy Design PatternStrategy Design Pattern
Strategy Design Pattern
 
Ngrx meta reducers
Ngrx meta reducersNgrx meta reducers
Ngrx meta reducers
 
Architecting your GWT applications with GWT-Platform - Lesson 02
Architecting your GWT applications with GWT-Platform - Lesson 02Architecting your GWT applications with GWT-Platform - Lesson 02
Architecting your GWT applications with GWT-Platform - Lesson 02
 
Android workshop
Android workshopAndroid workshop
Android workshop
 
F2
F2F2
F2
 
Unit testing with mock libs
Unit testing with mock libsUnit testing with mock libs
Unit testing with mock libs
 
droidparts
droidpartsdroidparts
droidparts
 
Diving in the Flex Data Binding Waters
Diving in the Flex Data Binding WatersDiving in the Flex Data Binding Waters
Diving in the Flex Data Binding Waters
 

Mehr von First Tuesday Bergen

How to innovate with Startups, from Bank to Chatbot @ First Tuesday Bergen
How to innovate with Startups, from Bank to Chatbot @ First Tuesday BergenHow to innovate with Startups, from Bank to Chatbot @ First Tuesday Bergen
How to innovate with Startups, from Bank to Chatbot @ First Tuesday BergenFirst Tuesday Bergen
 
Start smart – for bedre teamarbeid @ First Tuesday Bergen
Start smart – for bedre teamarbeid @ First Tuesday BergenStart smart – for bedre teamarbeid @ First Tuesday Bergen
Start smart – for bedre teamarbeid @ First Tuesday BergenFirst Tuesday Bergen
 
Hvordan bruke innovasjon til å få flere til å reise kollektivt? @ First Tuesd...
Hvordan bruke innovasjon til å få flere til å reise kollektivt? @ First Tuesd...Hvordan bruke innovasjon til å få flere til å reise kollektivt? @ First Tuesd...
Hvordan bruke innovasjon til å få flere til å reise kollektivt? @ First Tuesd...First Tuesday Bergen
 
Ewave - kutter strømregningen din med 26,8% @ First Tuesday Bergen
Ewave - kutter strømregningen din med 26,8% @ First Tuesday BergenEwave - kutter strømregningen din med 26,8% @ First Tuesday Bergen
Ewave - kutter strømregningen din med 26,8% @ First Tuesday BergenFirst Tuesday Bergen
 
Reisen til grønne forretningsmuligheter @ First Tuesday Bergen
Reisen til grønne forretningsmuligheter @ First Tuesday BergenReisen til grønne forretningsmuligheter @ First Tuesday Bergen
Reisen til grønne forretningsmuligheter @ First Tuesday BergenFirst Tuesday Bergen
 
Suksess ved hjelp av mentor @ First Tuesday Bergen
Suksess ved hjelp av mentor @ First Tuesday BergenSuksess ved hjelp av mentor @ First Tuesday Bergen
Suksess ved hjelp av mentor @ First Tuesday BergenFirst Tuesday Bergen
 
Mentor, rådgiver eller samtalepartner? @ First Tuesday Bergen
Mentor, rådgiver eller samtalepartner? @ First Tuesday BergenMentor, rådgiver eller samtalepartner? @ First Tuesday Bergen
Mentor, rådgiver eller samtalepartner? @ First Tuesday BergenFirst Tuesday Bergen
 
Produksjon av stortare - Gründer forteller om sin reise @ First Tuesday Bergen
Produksjon av stortare - Gründer forteller om sin reise @ First Tuesday BergenProduksjon av stortare - Gründer forteller om sin reise @ First Tuesday Bergen
Produksjon av stortare - Gründer forteller om sin reise @ First Tuesday BergenFirst Tuesday Bergen
 
Innovasjon Norge sitt beste gründertilbud? @ First Tuesday Bergen
Innovasjon Norge sitt beste gründertilbud? @ First Tuesday BergenInnovasjon Norge sitt beste gründertilbud? @ First Tuesday Bergen
Innovasjon Norge sitt beste gründertilbud? @ First Tuesday BergenFirst Tuesday Bergen
 
Hvordan vurdere investeringsmuligheter i tidlig fase @ First Tuesday Bergen
Hvordan vurdere investeringsmuligheter i tidlig fase @ First Tuesday BergenHvordan vurdere investeringsmuligheter i tidlig fase @ First Tuesday Bergen
Hvordan vurdere investeringsmuligheter i tidlig fase @ First Tuesday BergenFirst Tuesday Bergen
 
Quantfolio - Lager programvare som gir investeringsråd basert på kunstig inte...
Quantfolio - Lager programvare som gir investeringsråd basert på kunstig inte...Quantfolio - Lager programvare som gir investeringsråd basert på kunstig inte...
Quantfolio - Lager programvare som gir investeringsråd basert på kunstig inte...First Tuesday Bergen
 
WA - Jobbplattform som kobler bedrifter med talenter @ First Tuesday Bergen
WA - Jobbplattform som kobler bedrifter med talenter @ First Tuesday BergenWA - Jobbplattform som kobler bedrifter med talenter @ First Tuesday Bergen
WA - Jobbplattform som kobler bedrifter med talenter @ First Tuesday BergenFirst Tuesday Bergen
 
ProWellPlan - Automatisering av planlegging av boreoperasjoner @ First Tuesda...
ProWellPlan - Automatisering av planlegging av boreoperasjoner @ First Tuesda...ProWellPlan - Automatisering av planlegging av boreoperasjoner @ First Tuesda...
ProWellPlan - Automatisering av planlegging av boreoperasjoner @ First Tuesda...First Tuesday Bergen
 
Sobo Community - Lager europeisk nettbutikk for vintage klær @ First Tuesday ...
Sobo Community - Lager europeisk nettbutikk for vintage klær @ First Tuesday ...Sobo Community - Lager europeisk nettbutikk for vintage klær @ First Tuesday ...
Sobo Community - Lager europeisk nettbutikk for vintage klær @ First Tuesday ...First Tuesday Bergen
 
CeoBas - Nye løsninger for ballasthåndtering på skip @ First Tuesday Bergen
CeoBas - Nye løsninger for ballasthåndtering på skip @ First Tuesday BergenCeoBas - Nye løsninger for ballasthåndtering på skip @ First Tuesday Bergen
CeoBas - Nye løsninger for ballasthåndtering på skip @ First Tuesday BergenFirst Tuesday Bergen
 
Mecu - lager et digitalt verktøy som håndterer papirarbeidet ved sykdom og dø...
Mecu - lager et digitalt verktøy som håndterer papirarbeidet ved sykdom og dø...Mecu - lager et digitalt verktøy som håndterer papirarbeidet ved sykdom og dø...
Mecu - lager et digitalt verktøy som håndterer papirarbeidet ved sykdom og dø...First Tuesday Bergen
 
Jet Seafood - Lager ny handelsplattform for sjømat @ First Tuesday Bergen
Jet Seafood - Lager ny handelsplattform for sjømat @ First Tuesday BergenJet Seafood - Lager ny handelsplattform for sjømat @ First Tuesday Bergen
Jet Seafood - Lager ny handelsplattform for sjømat @ First Tuesday BergenFirst Tuesday Bergen
 

Mehr von First Tuesday Bergen (20)

How to innovate with Startups, from Bank to Chatbot @ First Tuesday Bergen
How to innovate with Startups, from Bank to Chatbot @ First Tuesday BergenHow to innovate with Startups, from Bank to Chatbot @ First Tuesday Bergen
How to innovate with Startups, from Bank to Chatbot @ First Tuesday Bergen
 
Start smart – for bedre teamarbeid @ First Tuesday Bergen
Start smart – for bedre teamarbeid @ First Tuesday BergenStart smart – for bedre teamarbeid @ First Tuesday Bergen
Start smart – for bedre teamarbeid @ First Tuesday Bergen
 
Hvordan bruke innovasjon til å få flere til å reise kollektivt? @ First Tuesd...
Hvordan bruke innovasjon til å få flere til å reise kollektivt? @ First Tuesd...Hvordan bruke innovasjon til å få flere til å reise kollektivt? @ First Tuesd...
Hvordan bruke innovasjon til å få flere til å reise kollektivt? @ First Tuesd...
 
Ewave - kutter strømregningen din med 26,8% @ First Tuesday Bergen
Ewave - kutter strømregningen din med 26,8% @ First Tuesday BergenEwave - kutter strømregningen din med 26,8% @ First Tuesday Bergen
Ewave - kutter strømregningen din med 26,8% @ First Tuesday Bergen
 
Reisen til grønne forretningsmuligheter @ First Tuesday Bergen
Reisen til grønne forretningsmuligheter @ First Tuesday BergenReisen til grønne forretningsmuligheter @ First Tuesday Bergen
Reisen til grønne forretningsmuligheter @ First Tuesday Bergen
 
Suksess ved hjelp av mentor @ First Tuesday Bergen
Suksess ved hjelp av mentor @ First Tuesday BergenSuksess ved hjelp av mentor @ First Tuesday Bergen
Suksess ved hjelp av mentor @ First Tuesday Bergen
 
Mentor, rådgiver eller samtalepartner? @ First Tuesday Bergen
Mentor, rådgiver eller samtalepartner? @ First Tuesday BergenMentor, rådgiver eller samtalepartner? @ First Tuesday Bergen
Mentor, rådgiver eller samtalepartner? @ First Tuesday Bergen
 
Produksjon av stortare - Gründer forteller om sin reise @ First Tuesday Bergen
Produksjon av stortare - Gründer forteller om sin reise @ First Tuesday BergenProduksjon av stortare - Gründer forteller om sin reise @ First Tuesday Bergen
Produksjon av stortare - Gründer forteller om sin reise @ First Tuesday Bergen
 
Innovasjon Norge sitt beste gründertilbud? @ First Tuesday Bergen
Innovasjon Norge sitt beste gründertilbud? @ First Tuesday BergenInnovasjon Norge sitt beste gründertilbud? @ First Tuesday Bergen
Innovasjon Norge sitt beste gründertilbud? @ First Tuesday Bergen
 
Hvordan vurdere investeringsmuligheter i tidlig fase @ First Tuesday Bergen
Hvordan vurdere investeringsmuligheter i tidlig fase @ First Tuesday BergenHvordan vurdere investeringsmuligheter i tidlig fase @ First Tuesday Bergen
Hvordan vurdere investeringsmuligheter i tidlig fase @ First Tuesday Bergen
 
Quantfolio - Lager programvare som gir investeringsråd basert på kunstig inte...
Quantfolio - Lager programvare som gir investeringsråd basert på kunstig inte...Quantfolio - Lager programvare som gir investeringsråd basert på kunstig inte...
Quantfolio - Lager programvare som gir investeringsråd basert på kunstig inte...
 
WA - Jobbplattform som kobler bedrifter med talenter @ First Tuesday Bergen
WA - Jobbplattform som kobler bedrifter med talenter @ First Tuesday BergenWA - Jobbplattform som kobler bedrifter med talenter @ First Tuesday Bergen
WA - Jobbplattform som kobler bedrifter med talenter @ First Tuesday Bergen
 
ProWellPlan - Automatisering av planlegging av boreoperasjoner @ First Tuesda...
ProWellPlan - Automatisering av planlegging av boreoperasjoner @ First Tuesda...ProWellPlan - Automatisering av planlegging av boreoperasjoner @ First Tuesda...
ProWellPlan - Automatisering av planlegging av boreoperasjoner @ First Tuesda...
 
Sobo Community - Lager europeisk nettbutikk for vintage klær @ First Tuesday ...
Sobo Community - Lager europeisk nettbutikk for vintage klær @ First Tuesday ...Sobo Community - Lager europeisk nettbutikk for vintage klær @ First Tuesday ...
Sobo Community - Lager europeisk nettbutikk for vintage klær @ First Tuesday ...
 
CeoBas - Nye løsninger for ballasthåndtering på skip @ First Tuesday Bergen
CeoBas - Nye løsninger for ballasthåndtering på skip @ First Tuesday BergenCeoBas - Nye løsninger for ballasthåndtering på skip @ First Tuesday Bergen
CeoBas - Nye løsninger for ballasthåndtering på skip @ First Tuesday Bergen
 
Mecu - lager et digitalt verktøy som håndterer papirarbeidet ved sykdom og dø...
Mecu - lager et digitalt verktøy som håndterer papirarbeidet ved sykdom og dø...Mecu - lager et digitalt verktøy som håndterer papirarbeidet ved sykdom og dø...
Mecu - lager et digitalt verktøy som håndterer papirarbeidet ved sykdom og dø...
 
Jet Seafood - Lager ny handelsplattform for sjømat @ First Tuesday Bergen
Jet Seafood - Lager ny handelsplattform for sjømat @ First Tuesday BergenJet Seafood - Lager ny handelsplattform for sjømat @ First Tuesday Bergen
Jet Seafood - Lager ny handelsplattform for sjømat @ First Tuesday Bergen
 
Meet Market Gravity
Meet Market GravityMeet Market Gravity
Meet Market Gravity
 
Bergen in Bergen - Løsning Lag 1
Bergen in Bergen - Løsning Lag 1Bergen in Bergen - Løsning Lag 1
Bergen in Bergen - Løsning Lag 1
 
Bergen in Bergen - Løsning Lag 2
Bergen in Bergen - Løsning Lag 2Bergen in Bergen - Løsning Lag 2
Bergen in Bergen - Løsning Lag 2
 

Kürzlich hochgeladen

SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhisoniya singh
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersThousandEyes
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxOnBoard
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksSoftradix Technologies
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitecturePixlogix Infotech
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...HostedbyConfluent
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Paola De la Torre
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...shyamraj55
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure servicePooja Nehwal
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
 

Kürzlich hochgeladen (20)

SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024
 
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | DelhiFULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
FULL ENJOY 🔝 8264348440 🔝 Call Girls in Diplomatic Enclave | Delhi
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptx
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other Frameworks
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC Architecture
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
 
Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101Salesforce Community Group Quito, Salesforce 101
Salesforce Community Group Quito, Salesforce 101
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
 

Automated Testing on Android with Dagger DI

  • 2. Dependency Injection Dagger Live Coding Sample 1 Live Coding Sample 2
  • 4. Why not automated tests on mobile?
  • 5. Motivation for Dependency Injection ● Decouple concrete from concrete ● Uniformity ● Reduced Dependency Carrying ● More Testable Code
  • 6. Decouple concrete from Concrete class MyStringUtils { private Context context; StringUtils(Context context) { this.context = context; } public String helloWorld() { return context.getString(R.string.hello_ciklum); } }
  • 7. Decouple concrete from Concrete class MainActivity extends Activity implements View.OnClickListener { @Inject MyStringUtils myStringUtils; void onCreate(Bundle savedInstanceState) { … } void onClick(View v) { MyStringUtils myStringUtils1 = new MyStringUtils(this.getApplication()); // new operator MyStringUtils myStringUtils2 = MyStringUtils.getInstance(this); // singleton pattern MyStringUtils myStringUtils3 = MyStringUtilsFactory.getInstance(this); // factory patterns String str1 myStr = MyStringUtils.helloWorld(this); // Static String str = myStringUtils.helloWorld(); TextView msgView = (TextView) findViewById(R.id.textView); msgView.setText(str); }}}
  • 8. Uniformity class MainActivity extends Activity implements View.OnClickListener { @Inject MyStringUtils myStringUtils; void onCreate(Bundle savedInstanceState) { … } void onClick(View v) { MyStringUtils myStringUtils1 = new MyStringUtils(this.getApplication()); // new instance MyStringUtils myStringUtils2 = MyStringUtils.getInstance(this); // Singleton pattern MyStringUtils myStringUtils3 = MyStringUtilsFactory.getInstance(this); // Factory pattern String str1 myStr = MyStringUtils.helloWorld(this); // Static String str = myStringUtils.helloWorld(); TextView msgView = (TextView) findViewById(R.id.textView); msgView.setText(str); } }}
  • 9. Dependency Carrying class MyActivity extends Activity { onClick(View v) { A a = new A(this); a.doSometing(); } } class A { Context mContext; public (Context mContext){ this.mContext = mContext; } public doSomething() { B b = new B(mContext); String str = b.getSomeString(R.strings.helloWorld); } } class B { Context mContext; public B(Context mContext) { this.mContext = mContext; } public String getSomeString(int resourceId) { return mContext.getString(resourceId); } }
  • 10. Reduced Dependency Carrying @Module class ProdModule { Context mContext; public ProdModule(Context mContext) { this.mContext = mContext; } @Provide B provideB() { return new B(context); } @Provide A provideA(B b) { return new A(b); } } class MyActivity { @Inject A a; onCreate(){ ((MyApplication)getApplication()).inject(this); } onClick(View v) { A a = new A(this); a.doSomething(); } } class A { @Inject B b; public doSomething() { String str = b.getSomeString(R.strings.helloWorld); } } class B { Context mContext; public B(Context mContext) { this.mContext = mContext; } public String getSomeString(int resourceId) { return mContext.getString(resourceId); } }
  • 11. More Testable Code class MainActivity extends Activity implements View.OnClickListener { @Inject MyStringUtils myStringUtils; void onCreate(Bundle savedInstanceState) { … } void onClick(View v) { String str = myStringUtils.helloWorld(); TextView msgView = (TextView) findViewById(R.id.textView); msgView.setText(str); } }}
  • 12. Other advantages ● More Reusable Code ● More Readable Code ● Reduced Dependencies
  • 13. Dependency Injection Dagger Live Coding Sample 1 Live Coding Sample 2
  • 15. Coffee maker public class CoffeMaker { @Inject Heater heater; @Inject Pump pump; public void brew() { heater.on(); pump.pump(); System.out.println("coffee!"); heater.off(); } }
  • 16. class Thermosiphon implements Pump { Heater heater; Thermosiphon(Heater heater) { this.heater = heater; } @Override public void pump() { if (heater.isHot()) { System.out.println("=> => pumping => =>"); } }
  • 17. Declare Dependencies class Thermosiphon implements Pump { Heater heater; @Inject Thermosiphon(Heater heater) { this.heater = heater; } }
  • 18. Satisfy Dependencies @Module class DripCoffeeModule { @Provides Heater provideHeater() { return new ElectricHeater(); } @Provides Pump providePump(Thermosiphon pump) { return pump; } }
  • 19. Build the Graph class CoffeeApp { public static void main(String[] args) { ObjectGraph objectGraph = ObjectGraph.create(new DripCoffeeModule()); CoffeeMaker coffeeMaker = objectGraph.get(CoffeeMaker.class); coffeeMaker.brew(); } }
  • 20. Neat features ● Lazy<T> ● Module overrides
  • 21. Lazy<T> class GridingCoffeeMaker { @Inject Lazy<Grinder> lazyGrinder; public void brew() { while (needsGrinding()) { // Grinder created once and cached. Grinder grinder = lazyGrinder.get() grinder.grind(); } } }
  • 22. Module Overrides @Module( includes = DripCoffeeModule.class, injects = CoffeeMakerTest.class, overrides = true ) static class TestModule { @Provides @Singleton Heater provideHeater() { return Mockito.mock(Heater.class); } }
  • 23. Dependency Injection Dagger Live Coding Sample 1 Live Coding Sample 2
  • 24. Live coding - Sample 1 ● add dependencies (with Gradle) ● create module ● set up Dagger in Application context ● inject dependencies to Activity ● create Activity test which injects a mock
  • 25. Add depedencies (Gradle) dependencies { ……... compile 'com.squareup.dagger:dagger:1.2.1' compile 'com.squareup.dagger:dagger-compiler:1.2.1' androidTestCompile 'org.mockito:mockito-core:1.9.5' androidTestCompile 'com.google.dexmaker:dexmaker:1.0' androidTestCompile 'com.google.dexmaker:dexmaker-mockito:1.0' }
  • 26. Module @Module( injects = { MyStringUtils.class, MainActivity.class }) class ProdModule { Application application; ProdModule(Application application){ this.application = application; } @Provides @Singleton MyStringUtils provideMyStringUtils() { return new MyStringUtils(application); }
  • 27. Define Dagger Application class MyApplication extends Application { ObjectGraph mGraph; void onCreate() { super.onCreate(); mGraph = ObjectGraph.create(getModules().toArray()); } void inject(Object o){ mGraph.inject(o); } List<Object> getModules() { List<Object> result = new ArrayList<Object>(); result.add(new ProdModule(this)); return result; }}
  • 28. Create MyStringUtils class MyStringUtils { MyStringUtils(Context context) { this.context = context; } public String helloWorld() { return context.getString(R.string.hello_ciklum); } }
  • 29. Inject dependencies Activity class MainActivity extends Activity { @Inject MyStringUtils myStringUtils; void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // set dependencies to this activity ((MyApplication)getApplication()).inject(this); setContentView(R.layout.activity_main); findViewById(R.id.button).setOnClickListener(this); }
  • 30. Unit test Activity with mock class MainActivityUnitTest extends ActivityUnitTestCase<MainActivity> { @Inject MyStringUtils myStringUtils; void setUp() { // create test application context, Dagger Graph with our test module. MyApplication application = new TestApplication(); application.inject(this); // inject the dependencies we need to this class setApplication(application); // use our custom test application context } void testOnClick() { String testingStr = "olala"; when(myStringUtils.helloWorld()).thenReturn(testingStr); this.activity = startActivity(intent, null, null); // the test View view = activity.findViewById(R.id.button); activity.onClick(view); // verify the mock was invoked verify(myStringUtils, times(1)).helloWorld(); // assert view got updated correctly TextView msgView = (TextView) activity.findViewById(R.id.textView); assertEquals(testingStr, msgView.getText()); }
  • 31. Dependency Injection Dagger Live Coding Sample 1 Live Coding Sample 2
  • 32. Sample app 2 ● Threads ● HTTP mocks
  • 33. Tips, tricks and Frameworks ● https://github.com/tha022/dagger-testing-example ● https://github.com/fizz-buzz/fb-android-dagger

Hinweis der Redaktion

  1. DI is a design pattern where you get your concrete things decoupled from your other concrete things - helps reusability and testability
  2. There are so many ways you can get hold of a instance of MyStringUtils, you could create a new instance with the new keyword, you could have implemented a Singleton pattern, you could have used a Factory pattern, or you could have called the method statically by provding the context as input.
  3. Allows uniformity. Is underestimated. If you use DI you have a pattern throughout your application. Every time you depend on something, this is how you do it. Every time you wanna expose your self as a dependency, this is how you do it. You dont have to worry about writing Factory classes or different patterns for looking things up, if you use DI its the same everywhere. this really helps as your application gets bigger, you can have new guys coming in to your team, and everything works the same way. I think uniformity is the secret sauce which we overlooked a lot when using DI.
  4. Since its the dependency container which now creates your dependency, not your concrete class, it can also be substituded by an other implementation by the dependency container. It can replace it with any other implement, like a mock. A mock can also be used without the class having to be an interface. Other times you want to inject a stub, then the dependency needs an interface.
  5. DAGer, really bad name, in good nerd spirit. It stands for Direct Acyclic Graph. Acyclic, you can’t depend on your self, not even transitively. This is to keep the framework simple. In for example Spring cycle dependencies are allowed, which makes Spring easy to use. Mark the difference between easy and simple. Easy to do for you as a programmer is not the same as the framework is simple, and the acyclic restriction in Dagger is a good example on the design tradeoffs they did.
  6. Now to show how Dagger works. We gonna use the same example as Dagger has on their website. So we have an coffee app, which has a coffee maker. The coffee maker works like this: It has a pump, which pumps the water through the hot water (the Heater). The pump is an interface, so you can plug in different implementations of a pump. In this example we have a Thermosiphon pumper, which means something like that - Thermosiphon (alt. thermosyphon) is a property of physics and refers to a method of passive heat exchange based on natural convection, which circulates a substance (liquid, or gas such as air) without the necessity of a mechanical pump. The coffee maker has two dependencies: a Pumo and a Heater. A Thermosiphon pump has a dependency to a heater, since it needs heat to move (pump) the water. The coffe maker has a method “brew”. the way it brew is to first start the heater (create the object and start the method “on”). Then its starts to pump the water through the heater, and when the pump is finished with doing so it turns off the heater. The coffee is served !
  7. Here is the Thermosiphon pump implementation. I have a dependency, but Im not gonna worry about how it gets injected in my concrete class. The Hollywood principle, I dont care how the dependency comes in, its someone elses problem, my job is to make the water pump. If the heater is turned on, ergo hot, then we’r ready to pump.
  8. But we havent yet declared that the Thermosiphon is a dependency which Dagger should handle. here is where Dagger comes in, how we declare our dependency, with the @Inject annotation. With this we say “hey framework, opt in here “. The Inject is standard of the Java javax package, so this code is portable among Guice, Spring, etc. This is the first of two ways to declare a dependency which Dagger should handle. After compiling the code, the bean processor will be applied, which makes Dagger do a scan of your classes and look for the @Inject annotation, and when found, write a binder wrapper class (more under internals)
  9. The other way of defining dependencies are like this. So we tell the framework, each time someone ask you for a dependency if a given type, this is how you provide them. What is really powerful is that these provide methods can have parameters passed in. The simplicity of Dagger is, this is the only way you define dependencies, ergo with Provide or with @Inject on the constructor.
  10. This is how we bootstrap the graph. We create the object graph by providing the module class where we have defined our dependencies / objects. In addition Dagger will, through the bean processor, look for other dependencies in your source by looking for @Inject.