SlideShare ist ein Scribd-Unternehmen logo
1 von 42
Downloaden Sie, um offline zu lesen
New Android build system
Flavored with Roboguice and Robolectric

Andreas Würl, Thomas Endres
Ultracode Meetup, 2013-11-13
Overview
A short introduction
New Android build system
Roboguice
Robolectric
The speakers
Andreas Würl is an IT consultant for TNG Technology
consulting currently working in Unterföhring. In his free
time, he is contributing to the Blitzortung app available for
Android and in development for iOS.
Thomas Endres is also an IT consultant for TNG
Technology consulting. In his free time, he is developing
software for controlling drones with bare hands, building
apps and contributing to HTML5 frameworks.
Our apps
Blitzortung
Simple to use map based application visualizing real time
lightning data provided by blitzortung.org. The current
thunderstorm situation at your fingertips.
Be Quiet - The noise alert
Whether you work in an office or in a class room, Be
Quiet will help you reduce noise. When the volume is too
high, it will blink and play a siren sound.
Overview
A short introduction
New Android build system
Roboguice
Robolectric
Building Android applications
Old school

Based on Ant
No built-in dependency management
Quite inflexible
Using old built-in library versions
No support for real unit tests
Test project needed for instrumentation tests
The build xml file
<target name="compile" depends="-resource-src, -aidl"
description="Compiles project's .java files into .class files">
<!-- ... -->
<javac encoding="ascii" target="1.5" debug="true" extdirs=""
destdir="${out.classes.absolute.dir}"
bootclasspathref="android.target.classpath"
verbose="${verbose}" classpath="${extensible.classpath}"
classpathref="android.libraries.jars">
<src path="${source.absolute.dir}" />
<src path="${gen.absolute.dir}" />
<src refid="android.libraries.src" />
<classpath>
<fileset dir="${external.libs.absolute.dir}" includes="*.jar" />
<fileset dir="${extensible.libs.classpath}" includes="*.jar" />
</classpath>
</javac>
</target>

Customization is very difficult
Building Android applications
The alternative

Based on Maven → Maven plugin
Allows for dependency management
A lot more flexible
→ But still far from being perfect
Real unit tests are possible
Still using a test project for instrumentation tests
The POM file
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.tngtech.internal.android</groupId>
<artifactId>android-demo</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>apk</packaging>
<dependencies>
<dependency>
<groupId>com.google.android</groupId>
<artifactId>android</artifactId>
<version>${platform.version}</version>
<scope>provided</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>com.jayway.maven.plugins.android.generation2</groupId>
<artifactId>android-maven-plugin</artifactId>
<version>3.7.0</version>
<configuration>
<androidManifestFile>${project.basedir}/AndroidManifest.xml</androidManifestFile>
<assetsDirectory>${project.basedir}/assets</assetsDirectory>
<resourceDirectory>${project.basedir}/res</resourceDirectory>
<sdk><platform>18</platform></sdk>
</configuration>
</plugin>
</plugins>
</build>
</project>
Building Android applications
The new way

Based on Gradle → Gradle-Plugin
Built-in dependency management
Using common Java patterns
→ But flexible enough to change that
Real unit tests through plugins
Instrumentation tests within the same project
The Gradle build file
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath 'com.android.tools.build:gradle:0.6.+'
}
}
apply plugin: 'android'
repositories {
mavenCentral()
}
dependencies {
// Put all dependencies here
}
android {
compileSdkVersion 18
buildToolsVersion "18.1.1"
defaultConfig {
minSdkVersion 18
targetSdkVersion 18
}
}
Android Studio
Android Studio
The facts

Based on IntelliJ
Ready to use
No additional plugins needed
Brings shortcuts for AVD and SDK manager
Out of the box support for the new build system
Possibility to migrate old projects
Overview
A short introduction
New Android build system
Roboguice
Robolectric
What the heck is Roboguice?
A dependency injection container
An implementation of JSR 330
A fork of the Guice framework for the JDK
Easy to configure and to use
Dependency injection

Instead of taking

public class MainActivity extends Activity{
private LocationManager locationManager;
public void onCreate(Bundle savedInstance) {
// ...
locationManager = (LocationManager)
getSystemService(Activity.LOCATION_SERVICE);
}
}

be given
public class MainActivity extends RoboActivity{
@Inject
private LocationManager locationManager;
public void onCreate(Bundle savedInstance) {
// ...
}
}
Principles of DI
Don't let a class create objects on its own
Instead, pass them the objects they need
Then you can exchange them for test purposes
You can pass in test doubles
But you can also exchange the "real" object easily
Loose coupling becomes a reality
How can you inject objects?
Through the constructor:

@Inject
public MainActivity(LocationManager locationManager) {
// ...
this.locationManager = locationManager;
}

Into the field itself:
@Inject
private LocationManager locationManager;

Into a property:
@Inject
public void setLocationManager(LocationManager locationManager) {
this.locationManager = locationManager;
}
What can be injected?
Arbitrary objects with a zero-arg constructor
Objects with a constructor managed by Roboguice
Views:
@InjectView(R.id.specialButton)
private Button button;

Resources:
@InjectResource(R.drawable.specialPicture)
private Drawable picture;

A lot of standard Android objects:
LocationManager, AssetManager, ...
AlarmManager, NotificationManager, ...
Vibrator
Robo* classes
For DI to work, you have to extend the robo classes:
Use them instead of the standard Android classes
RoboActivity instead of Activity
RoboListActivity instead of ListActivity
RoboService instead of Service
RoboFragment instead of Fragment
...
Injecting providers:
Sometimes, you need more than one object of a class
public class SomeObjectProvider implements Provider<SomeObject> {
@Inject
private SomeOtherObject someOtherObject;
@Override
public SomeObject get() {
return new SomeObject(someOtherObject);
}
}
private class SomeObjectUser {
@Inject
private Provider<SomeObject> someObjectProvider;
private SomeObject getObject() {
return someObjectProvider.get();
}
}
Injecting injectors
You can also inject an injector
Then, you can get arbitrary objects out of the injector
@Inject
private Injector injector;
public <T> T giveMeAnObjectOf(Class<T> clazz) {
return injector.getInstance(clazz);
}
Configuration
By defining a module, you can configure the objects injected
public class SomeModule extends AbstractModule {
@Override
public void configure() {
// Bind an interface to a specific class
bind(SomeInterface.class).to(SomeImplementation.class);
// Bind a standard provider to the class
bind(SomeClass.class).toProvider(SomeClassProvider.class);
}
}

Modules are discovered via "roboguice_modules.xml"
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string-array name="roboguice_modules">
<item>com.mypackage.SomeModule</item>
</string-array>
</resources>
Integrate Roboguice (1)
Add roboguice to the compile dependencies:
// build.gradle
dependencies {
// ...
compile 'roboguice:roboguice:2.+'
}

Extend the Robo* classes in your objects:
public class SomeActivity extends RoboActivity {
// ...
}

Inject your dependencies:
@Inject
private SomeObject someObject;
Integrate Roboguice (2)
Configure the module:
public class SomeModule extends AbstractModule {
@Override
protected void configure() {
bind(SomeClass.class).toProvider(SomeClassProvider.class);
// ...
}
}

Register the module:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string-array name="roboguice_modules">
<item>com.mypackage.SomeModule</item>
</string-array>
</resources>

Write unit tests:
public class SomeActivityTest {
// How to do that?
}
Overview
A short introduction
New Android build system
Roboguice
Robolectric
Android testing
in new build system

Based on JUnit3
Requires separate test project
Requires emulator or device for execution
Lacks real mocking
But initial support for some frameworks
Can I run tests locally?
No. It's impossible!
Any method of the SDK will throw the following
exception when called:
java.lang.RuntimeException: Stub!
at android.*

Why is that?
Android SDK jars for development only contain method stubs
Is there a solution?
Yes! Use Robolectric
What the heck is Robolectric?
Android SDK wrapper/enabler for local test execution
Just another dependency of your project
Sometimes dependency order is important
Uses some magic to enable use of the stubbed SDK jars
Unfortunately not yet complete
What do I get?
Tests are running on the dev machine
Current version of JUnit 4 is used
Any Mock- or Match-Framework can be used
Can be used in parallel with instrumentation tests
How do I enable Robolectric?
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath 'com.android.tools.build:gradle:0.6.+'
classpath 'com.squareup.gradle:gradle-android-test-plugin:0.9.+'
}
}
apply plugin: 'android'
apply plugin: 'android-test'
...
How do I implement a test?
Just use the RobolectricTestRunner
@RunWith(RobolectricTestRunner.class)
class SomeActivityTest {
@Before
public void setUp() {
// Preparation for every test
}
@Test
public void testSomething() {
// Your test code belongs here
assertThat(1, is(not(2));
}
}
Basic concepts
Shadows

TextView textView = (TextView) mainActivity.findViewById(R.id.helloWorld);
final ShadowTextView shadowTextView = Robolectric.shadowOf(textView);
assertThat(shadowTextView.innerText(), is("Hello World!"));

Implementation in Robolectric
@Implements(TextView.class)
public class ShadowTextView extends ShadowView {
@RealObject TextView realTextView;
@Override
public String innerText() {
CharSequence text = realTextView.getText();
return (text == null || realTextView.getVisibility() != View.VISIBLE) ? "" : text.toString();
}
@Implementation
public void setPaintFlags(int paintFlags) {
this.paintFlags = paintFlags;
}
}
Basic concepts

Robolectric builds up a full application context
Activities can be built
activity = Robolectric.buildActivity(MainActivity.class).create().get();

Testing resource access is possible as well
Resources resources = Robolectric.application.getResources();
assertThat(resources.getColor(R.color.Red), is(0xffff0000));

Modify preferences for tests
SharedPreferences defaultSharedPreferences =
ShadowPreferenceManager.getDefaultSharedPreferences(
Robolectric.application);
defaultSharedPreferences.edit()
.putBoolean("test", true).putFloat("limit", 1.0f).apply();
But ...

Android Studio integration is not yet available
Tests can be run via gradle task 'test'
> gradle test

IDE support only through ugly hacks
Summary

The new build system is a lot more flexible than the old one
Android Studio is a cool new tool for app development
It comes bundled with the SDK, you can start development
immediately
But there are still some issues with it
Roboguice makes it possbible to decouple your application
Robolectric can be used for local test execution
Thank you!

Are there any questions?

andreas.wuerl@tngtech.com, thomas.endres@tngtech.com

Weitere ähnliche Inhalte

Was ist angesagt?

Android Studio vs Eclipse: What are the main differences?
Android Studio vs Eclipse: What are the main differences?Android Studio vs Eclipse: What are the main differences?
Android Studio vs Eclipse: What are the main differences?avocarrot
 
Latest & interesting updates #android dev
Latest & interesting updates #android devLatest & interesting updates #android dev
Latest & interesting updates #android devParesh Mayani
 
Exploring Android Studio
Exploring Android StudioExploring Android Studio
Exploring Android StudioAkshay Chordiya
 
Head first android apps dev tools
Head first android apps dev toolsHead first android apps dev tools
Head first android apps dev toolsShaka Huang
 
Comparison between Eclipse and Android Studio for Android Development
Comparison between Eclipse and Android Studio for Android DevelopmentComparison between Eclipse and Android Studio for Android Development
Comparison between Eclipse and Android Studio for Android DevelopmentWillow Cheng
 
Mobile Day - Intel XDK & Testing
Mobile Day - Intel XDK & TestingMobile Day - Intel XDK & Testing
Mobile Day - Intel XDK & TestingSoftware Guru
 
Android Studio 3 - Dependency-Aware Build Variants and Product Flavors
Android Studio 3 - Dependency-Aware Build Variants and Product FlavorsAndroid Studio 3 - Dependency-Aware Build Variants and Product Flavors
Android Studio 3 - Dependency-Aware Build Variants and Product FlavorsStefan Martynkiw
 
How to setup unit testing in Android Studio
How to setup unit testing in Android StudioHow to setup unit testing in Android Studio
How to setup unit testing in Android Studiotobiaspreuss
 
Intro to Eclipse Che, by Tyler Jewell
Intro to Eclipse Che, by Tyler JewellIntro to Eclipse Che, by Tyler Jewell
Intro to Eclipse Che, by Tyler Jewelljwi11iams
 
Introduction to Eclipse Che / EclipseCon 2014
Introduction to Eclipse Che / EclipseCon 2014Introduction to Eclipse Che / EclipseCon 2014
Introduction to Eclipse Che / EclipseCon 2014Florent BENOIT
 
#Code2Create:: Introduction to App Development in Flutter with Dart
#Code2Create:: Introduction to App Development in Flutter with Dart#Code2Create:: Introduction to App Development in Flutter with Dart
#Code2Create:: Introduction to App Development in Flutter with DartGDGKuwaitGoogleDevel
 
Rapid Android Development for Hackathon
Rapid Android Development for HackathonRapid Android Development for Hackathon
Rapid Android Development for HackathonCodePolitan
 
Experiences building apps with React Native @DomCode 2016
Experiences building apps with React Native @DomCode 2016Experiences building apps with React Native @DomCode 2016
Experiences building apps with React Native @DomCode 2016Adrian Philipp
 
Getting Started with Cross-Platform Mobile Development with Flutter and Dart
Getting Started with Cross-Platform Mobile Development with Flutter and DartGetting Started with Cross-Platform Mobile Development with Flutter and Dart
Getting Started with Cross-Platform Mobile Development with Flutter and DartHarshith Keni
 
From zero to hero with React Native!
From zero to hero with React Native!From zero to hero with React Native!
From zero to hero with React Native!Commit University
 
Building your Own Mobile Enterprise Application: It’s Not as Hard as You Migh...
Building your Own Mobile Enterprise Application: It’s Not as Hard as You Migh...Building your Own Mobile Enterprise Application: It’s Not as Hard as You Migh...
Building your Own Mobile Enterprise Application: It’s Not as Hard as You Migh...Jason Conger
 

Was ist angesagt? (20)

Android Studio vs Eclipse: What are the main differences?
Android Studio vs Eclipse: What are the main differences?Android Studio vs Eclipse: What are the main differences?
Android Studio vs Eclipse: What are the main differences?
 
Latest & interesting updates #android dev
Latest & interesting updates #android devLatest & interesting updates #android dev
Latest & interesting updates #android dev
 
Exploring Android Studio
Exploring Android StudioExploring Android Studio
Exploring Android Studio
 
Head first android apps dev tools
Head first android apps dev toolsHead first android apps dev tools
Head first android apps dev tools
 
Comparison between Eclipse and Android Studio for Android Development
Comparison between Eclipse and Android Studio for Android DevelopmentComparison between Eclipse and Android Studio for Android Development
Comparison between Eclipse and Android Studio for Android Development
 
React Native
React NativeReact Native
React Native
 
Mobile Day - Intel XDK & Testing
Mobile Day - Intel XDK & TestingMobile Day - Intel XDK & Testing
Mobile Day - Intel XDK & Testing
 
Android Studio 3 - Dependency-Aware Build Variants and Product Flavors
Android Studio 3 - Dependency-Aware Build Variants and Product FlavorsAndroid Studio 3 - Dependency-Aware Build Variants and Product Flavors
Android Studio 3 - Dependency-Aware Build Variants and Product Flavors
 
How to setup unit testing in Android Studio
How to setup unit testing in Android StudioHow to setup unit testing in Android Studio
How to setup unit testing in Android Studio
 
Intro to Eclipse Che, by Tyler Jewell
Intro to Eclipse Che, by Tyler JewellIntro to Eclipse Che, by Tyler Jewell
Intro to Eclipse Che, by Tyler Jewell
 
Introduction to Eclipse Che / EclipseCon 2014
Introduction to Eclipse Che / EclipseCon 2014Introduction to Eclipse Che / EclipseCon 2014
Introduction to Eclipse Che / EclipseCon 2014
 
#Code2Create:: Introduction to App Development in Flutter with Dart
#Code2Create:: Introduction to App Development in Flutter with Dart#Code2Create:: Introduction to App Development in Flutter with Dart
#Code2Create:: Introduction to App Development in Flutter with Dart
 
Rapid Android Development for Hackathon
Rapid Android Development for HackathonRapid Android Development for Hackathon
Rapid Android Development for Hackathon
 
Nativescript with angular 2
Nativescript with angular 2Nativescript with angular 2
Nativescript with angular 2
 
Experiences building apps with React Native @DomCode 2016
Experiences building apps with React Native @DomCode 2016Experiences building apps with React Native @DomCode 2016
Experiences building apps with React Native @DomCode 2016
 
Getting Started with Cross-Platform Mobile Development with Flutter and Dart
Getting Started with Cross-Platform Mobile Development with Flutter and DartGetting Started with Cross-Platform Mobile Development with Flutter and Dart
Getting Started with Cross-Platform Mobile Development with Flutter and Dart
 
From zero to hero with React Native!
From zero to hero with React Native!From zero to hero with React Native!
From zero to hero with React Native!
 
Fastlane
FastlaneFastlane
Fastlane
 
Building your Own Mobile Enterprise Application: It’s Not as Hard as You Migh...
Building your Own Mobile Enterprise Application: It’s Not as Hard as You Migh...Building your Own Mobile Enterprise Application: It’s Not as Hard as You Migh...
Building your Own Mobile Enterprise Application: It’s Not as Hard as You Migh...
 
Flutter 1
Flutter 1Flutter 1
Flutter 1
 

Ähnlich wie [Ultracode Munich #4] Short introduction to the new Android build system including Android Studio, Roboguice and Robolectric

React Native for multi-platform mobile applications
React Native for multi-platform mobile applicationsReact Native for multi-platform mobile applications
React Native for multi-platform mobile applicationsMatteo Manchi
 
Testing in Android: automatici, di integrazione, TDD e scenari avanzati
Testing in Android: automatici, di integrazione, TDD e scenari avanzatiTesting in Android: automatici, di integrazione, TDD e scenari avanzati
Testing in Android: automatici, di integrazione, TDD e scenari avanzatiAlfredo Morresi
 
Android - Open Source Bridge 2011
Android - Open Source Bridge 2011Android - Open Source Bridge 2011
Android - Open Source Bridge 2011sullis
 
Module-I_Introduction-to-Android.pptx
Module-I_Introduction-to-Android.pptxModule-I_Introduction-to-Android.pptx
Module-I_Introduction-to-Android.pptxlancelotlaytan1996
 
Writing Android Libraries
Writing Android LibrariesWriting Android Libraries
Writing Android Librariesemanuelez
 
Android Programming made easy
Android Programming made easyAndroid Programming made easy
Android Programming made easyLars Vogel
 
From Containerization to Modularity
From Containerization to ModularityFrom Containerization to Modularity
From Containerization to Modularityoasisfeng
 
Android presentation
Android presentationAndroid presentation
Android presentationImam Raza
 
Android developer's toolbox
Android developer's toolboxAndroid developer's toolbox
Android developer's toolboxAlex Verdyan
 
Innovation Generation - The Mobile Meetup: Android Best Practices
Innovation Generation - The Mobile Meetup: Android Best PracticesInnovation Generation - The Mobile Meetup: Android Best Practices
Innovation Generation - The Mobile Meetup: Android Best PracticesSolstice Mobile Argentina
 
Android Introduction on Java Forum Stuttgart 11
Android Introduction on Java Forum Stuttgart 11 Android Introduction on Java Forum Stuttgart 11
Android Introduction on Java Forum Stuttgart 11 Lars Vogel
 
Android studio
Android studioAndroid studio
Android studioAndri Yabu
 
Jdk Tools For Performance Diagnostics
Jdk Tools For Performance DiagnosticsJdk Tools For Performance Diagnostics
Jdk Tools For Performance DiagnosticsDror Bereznitsky
 
Android Jumpstart Jfokus
Android Jumpstart JfokusAndroid Jumpstart Jfokus
Android Jumpstart JfokusLars Vogel
 
Android testing
Android testingAndroid testing
Android testingBitbar
 

Ähnlich wie [Ultracode Munich #4] Short introduction to the new Android build system including Android Studio, Roboguice and Robolectric (20)

React Native for multi-platform mobile applications
React Native for multi-platform mobile applicationsReact Native for multi-platform mobile applications
React Native for multi-platform mobile applications
 
Testing in Android: automatici, di integrazione, TDD e scenari avanzati
Testing in Android: automatici, di integrazione, TDD e scenari avanzatiTesting in Android: automatici, di integrazione, TDD e scenari avanzati
Testing in Android: automatici, di integrazione, TDD e scenari avanzati
 
Android - Open Source Bridge 2011
Android - Open Source Bridge 2011Android - Open Source Bridge 2011
Android - Open Source Bridge 2011
 
Android
AndroidAndroid
Android
 
Module-I_Introduction-to-Android.pptx
Module-I_Introduction-to-Android.pptxModule-I_Introduction-to-Android.pptx
Module-I_Introduction-to-Android.pptx
 
Writing Android Libraries
Writing Android LibrariesWriting Android Libraries
Writing Android Libraries
 
Android Programming made easy
Android Programming made easyAndroid Programming made easy
Android Programming made easy
 
From Containerization to Modularity
From Containerization to ModularityFrom Containerization to Modularity
From Containerization to Modularity
 
Android presentation
Android presentationAndroid presentation
Android presentation
 
Android developer's toolbox
Android developer's toolboxAndroid developer's toolbox
Android developer's toolbox
 
Innovation Generation - The Mobile Meetup: Android Best Practices
Innovation Generation - The Mobile Meetup: Android Best PracticesInnovation Generation - The Mobile Meetup: Android Best Practices
Innovation Generation - The Mobile Meetup: Android Best Practices
 
Android dev o_auth
Android dev o_authAndroid dev o_auth
Android dev o_auth
 
Android Introduction on Java Forum Stuttgart 11
Android Introduction on Java Forum Stuttgart 11 Android Introduction on Java Forum Stuttgart 11
Android Introduction on Java Forum Stuttgart 11
 
Android studio
Android studioAndroid studio
Android studio
 
Jdk Tools For Performance Diagnostics
Jdk Tools For Performance DiagnosticsJdk Tools For Performance Diagnostics
Jdk Tools For Performance Diagnostics
 
Android Jumpstart Jfokus
Android Jumpstart JfokusAndroid Jumpstart Jfokus
Android Jumpstart Jfokus
 
Android testing
Android testingAndroid testing
Android testing
 
Intro to Android Programming
Intro to Android ProgrammingIntro to Android Programming
Intro to Android Programming
 
Synapseindia android apps application
Synapseindia android apps applicationSynapseindia android apps application
Synapseindia android apps application
 
Core Android
Core AndroidCore Android
Core Android
 

Mehr von BeMyApp

Introduction to epid
Introduction to epidIntroduction to epid
Introduction to epidBeMyApp
 
Introduction ciot workshop premeetup
Introduction ciot workshop premeetupIntroduction ciot workshop premeetup
Introduction ciot workshop premeetupBeMyApp
 
Présentation des APIs cognitives IBM Watson
Présentation des APIs cognitives IBM WatsonPrésentation des APIs cognitives IBM Watson
Présentation des APIs cognitives IBM WatsonBeMyApp
 
Crédit Agricole S.A. Personae et Parcours
Crédit Agricole S.A. Personae et ParcoursCrédit Agricole S.A. Personae et Parcours
Crédit Agricole S.A. Personae et ParcoursBeMyApp
 
Cisco Paris DevNet Hackathon slideshow - Intro
Cisco Paris DevNet Hackathon slideshow - IntroCisco Paris DevNet Hackathon slideshow - Intro
Cisco Paris DevNet Hackathon slideshow - IntroBeMyApp
 
Tumeurs Neuroendocrines : une vue d'ensemble
Tumeurs Neuroendocrines : une vue d'ensembleTumeurs Neuroendocrines : une vue d'ensemble
Tumeurs Neuroendocrines : une vue d'ensembleBeMyApp
 
Building your first game in Unity 3d by Sarah Sexton
Building your first game in Unity 3d  by Sarah SextonBuilding your first game in Unity 3d  by Sarah Sexton
Building your first game in Unity 3d by Sarah SextonBeMyApp
 
Using intel's real sense to create games with natural user interfaces justi...
Using intel's real sense to create games with natural user interfaces   justi...Using intel's real sense to create games with natural user interfaces   justi...
Using intel's real sense to create games with natural user interfaces justi...BeMyApp
 
Introduction to using the R200 camera & Realsense SDK in Unity3d - Jon Collins
Introduction to using the R200 camera & Realsense SDK in Unity3d - Jon CollinsIntroduction to using the R200 camera & Realsense SDK in Unity3d - Jon Collins
Introduction to using the R200 camera & Realsense SDK in Unity3d - Jon CollinsBeMyApp
 
Audio Mixer in Unity5 - Andy Touch
Audio Mixer in Unity5 - Andy TouchAudio Mixer in Unity5 - Andy Touch
Audio Mixer in Unity5 - Andy TouchBeMyApp
 
Shaders - Claudia Doppioslash - Unity With the Best
Shaders - Claudia Doppioslash - Unity With the BestShaders - Claudia Doppioslash - Unity With the Best
Shaders - Claudia Doppioslash - Unity With the BestBeMyApp
 
[HACKATHON CISCO PARIS] Slideshow du workshop Smart City
[HACKATHON CISCO PARIS] Slideshow du workshop Smart City[HACKATHON CISCO PARIS] Slideshow du workshop Smart City
[HACKATHON CISCO PARIS] Slideshow du workshop Smart CityBeMyApp
 
Tools to Save Time
Tools to Save TimeTools to Save Time
Tools to Save TimeBeMyApp
 
[Workshop e résidents] présentation intent, craft ai, dalkia et incubateur
[Workshop e résidents] présentation intent, craft ai, dalkia et incubateur[Workshop e résidents] présentation intent, craft ai, dalkia et incubateur
[Workshop e résidents] présentation intent, craft ai, dalkia et incubateurBeMyApp
 
[Webinar E-résidents #1] Présentation des différents métiers du bâtiment conn...
[Webinar E-résidents #1] Présentation des différents métiers du bâtiment conn...[Webinar E-résidents #1] Présentation des différents métiers du bâtiment conn...
[Webinar E-résidents #1] Présentation des différents métiers du bâtiment conn...BeMyApp
 
[IoT World Forum Webinar] Review of CMX Cisco technology
[IoT World Forum Webinar] Review of CMX Cisco technology[IoT World Forum Webinar] Review of CMX Cisco technology
[IoT World Forum Webinar] Review of CMX Cisco technologyBeMyApp
 
HP Helion Episode 6: Cloud Foundry Summit Recap
HP Helion Episode 6: Cloud Foundry Summit RecapHP Helion Episode 6: Cloud Foundry Summit Recap
HP Helion Episode 6: Cloud Foundry Summit RecapBeMyApp
 
Webinar UI/UX by Francesco Marcellino
Webinar UI/UX by Francesco MarcellinoWebinar UI/UX by Francesco Marcellino
Webinar UI/UX by Francesco MarcellinoBeMyApp
 
HP Helion Webinar #5 - Security Beyond Firewalls
HP Helion Webinar #5 - Security Beyond FirewallsHP Helion Webinar #5 - Security Beyond Firewalls
HP Helion Webinar #5 - Security Beyond FirewallsBeMyApp
 
HP Helion Webinar #4 - Open stack the magic pill
HP Helion Webinar #4 - Open stack the magic pillHP Helion Webinar #4 - Open stack the magic pill
HP Helion Webinar #4 - Open stack the magic pillBeMyApp
 

Mehr von BeMyApp (20)

Introduction to epid
Introduction to epidIntroduction to epid
Introduction to epid
 
Introduction ciot workshop premeetup
Introduction ciot workshop premeetupIntroduction ciot workshop premeetup
Introduction ciot workshop premeetup
 
Présentation des APIs cognitives IBM Watson
Présentation des APIs cognitives IBM WatsonPrésentation des APIs cognitives IBM Watson
Présentation des APIs cognitives IBM Watson
 
Crédit Agricole S.A. Personae et Parcours
Crédit Agricole S.A. Personae et ParcoursCrédit Agricole S.A. Personae et Parcours
Crédit Agricole S.A. Personae et Parcours
 
Cisco Paris DevNet Hackathon slideshow - Intro
Cisco Paris DevNet Hackathon slideshow - IntroCisco Paris DevNet Hackathon slideshow - Intro
Cisco Paris DevNet Hackathon slideshow - Intro
 
Tumeurs Neuroendocrines : une vue d'ensemble
Tumeurs Neuroendocrines : une vue d'ensembleTumeurs Neuroendocrines : une vue d'ensemble
Tumeurs Neuroendocrines : une vue d'ensemble
 
Building your first game in Unity 3d by Sarah Sexton
Building your first game in Unity 3d  by Sarah SextonBuilding your first game in Unity 3d  by Sarah Sexton
Building your first game in Unity 3d by Sarah Sexton
 
Using intel's real sense to create games with natural user interfaces justi...
Using intel's real sense to create games with natural user interfaces   justi...Using intel's real sense to create games with natural user interfaces   justi...
Using intel's real sense to create games with natural user interfaces justi...
 
Introduction to using the R200 camera & Realsense SDK in Unity3d - Jon Collins
Introduction to using the R200 camera & Realsense SDK in Unity3d - Jon CollinsIntroduction to using the R200 camera & Realsense SDK in Unity3d - Jon Collins
Introduction to using the R200 camera & Realsense SDK in Unity3d - Jon Collins
 
Audio Mixer in Unity5 - Andy Touch
Audio Mixer in Unity5 - Andy TouchAudio Mixer in Unity5 - Andy Touch
Audio Mixer in Unity5 - Andy Touch
 
Shaders - Claudia Doppioslash - Unity With the Best
Shaders - Claudia Doppioslash - Unity With the BestShaders - Claudia Doppioslash - Unity With the Best
Shaders - Claudia Doppioslash - Unity With the Best
 
[HACKATHON CISCO PARIS] Slideshow du workshop Smart City
[HACKATHON CISCO PARIS] Slideshow du workshop Smart City[HACKATHON CISCO PARIS] Slideshow du workshop Smart City
[HACKATHON CISCO PARIS] Slideshow du workshop Smart City
 
Tools to Save Time
Tools to Save TimeTools to Save Time
Tools to Save Time
 
[Workshop e résidents] présentation intent, craft ai, dalkia et incubateur
[Workshop e résidents] présentation intent, craft ai, dalkia et incubateur[Workshop e résidents] présentation intent, craft ai, dalkia et incubateur
[Workshop e résidents] présentation intent, craft ai, dalkia et incubateur
 
[Webinar E-résidents #1] Présentation des différents métiers du bâtiment conn...
[Webinar E-résidents #1] Présentation des différents métiers du bâtiment conn...[Webinar E-résidents #1] Présentation des différents métiers du bâtiment conn...
[Webinar E-résidents #1] Présentation des différents métiers du bâtiment conn...
 
[IoT World Forum Webinar] Review of CMX Cisco technology
[IoT World Forum Webinar] Review of CMX Cisco technology[IoT World Forum Webinar] Review of CMX Cisco technology
[IoT World Forum Webinar] Review of CMX Cisco technology
 
HP Helion Episode 6: Cloud Foundry Summit Recap
HP Helion Episode 6: Cloud Foundry Summit RecapHP Helion Episode 6: Cloud Foundry Summit Recap
HP Helion Episode 6: Cloud Foundry Summit Recap
 
Webinar UI/UX by Francesco Marcellino
Webinar UI/UX by Francesco MarcellinoWebinar UI/UX by Francesco Marcellino
Webinar UI/UX by Francesco Marcellino
 
HP Helion Webinar #5 - Security Beyond Firewalls
HP Helion Webinar #5 - Security Beyond FirewallsHP Helion Webinar #5 - Security Beyond Firewalls
HP Helion Webinar #5 - Security Beyond Firewalls
 
HP Helion Webinar #4 - Open stack the magic pill
HP Helion Webinar #4 - Open stack the magic pillHP Helion Webinar #4 - Open stack the magic pill
HP Helion Webinar #4 - Open stack the magic pill
 

Kürzlich hochgeladen

From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .Alan Dix
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningLars Bell
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteDianaGray10
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Enterprise Knowledge
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...Fwdays
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionDilum Bandara
 
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo DayH2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo DaySri Ambati
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Manik S Magar
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfRankYa
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 

Kürzlich hochgeladen (20)

From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .From Family Reminiscence to Scholarly Archive .
From Family Reminiscence to Scholarly Archive .
 
DSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine TuningDSPy a system for AI to Write Prompts and Do Fine Tuning
DSPy a system for AI to Write Prompts and Do Fine Tuning
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 
Take control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test SuiteTake control of your SAP testing with UiPath Test Suite
Take control of your SAP testing with UiPath Test Suite
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
 
Advanced Computer Architecture – An Introduction
Advanced Computer Architecture – An IntroductionAdvanced Computer Architecture – An Introduction
Advanced Computer Architecture – An Introduction
 
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo DayH2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
H2O.ai CEO/Founder: Sri Ambati Keynote at Wells Fargo Day
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
Search Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdfSearch Engine Optimization SEO PDF for 2024.pdf
Search Engine Optimization SEO PDF for 2024.pdf
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 

[Ultracode Munich #4] Short introduction to the new Android build system including Android Studio, Roboguice and Robolectric

  • 1. New Android build system Flavored with Roboguice and Robolectric Andreas Würl, Thomas Endres Ultracode Meetup, 2013-11-13
  • 2. Overview A short introduction New Android build system Roboguice Robolectric
  • 3. The speakers Andreas Würl is an IT consultant for TNG Technology consulting currently working in Unterföhring. In his free time, he is contributing to the Blitzortung app available for Android and in development for iOS. Thomas Endres is also an IT consultant for TNG Technology consulting. In his free time, he is developing software for controlling drones with bare hands, building apps and contributing to HTML5 frameworks.
  • 4. Our apps Blitzortung Simple to use map based application visualizing real time lightning data provided by blitzortung.org. The current thunderstorm situation at your fingertips. Be Quiet - The noise alert Whether you work in an office or in a class room, Be Quiet will help you reduce noise. When the volume is too high, it will blink and play a siren sound.
  • 5. Overview A short introduction New Android build system Roboguice Robolectric
  • 6. Building Android applications Old school Based on Ant No built-in dependency management Quite inflexible Using old built-in library versions No support for real unit tests Test project needed for instrumentation tests
  • 7. The build xml file <target name="compile" depends="-resource-src, -aidl" description="Compiles project's .java files into .class files"> <!-- ... --> <javac encoding="ascii" target="1.5" debug="true" extdirs="" destdir="${out.classes.absolute.dir}" bootclasspathref="android.target.classpath" verbose="${verbose}" classpath="${extensible.classpath}" classpathref="android.libraries.jars"> <src path="${source.absolute.dir}" /> <src path="${gen.absolute.dir}" /> <src refid="android.libraries.src" /> <classpath> <fileset dir="${external.libs.absolute.dir}" includes="*.jar" /> <fileset dir="${extensible.libs.classpath}" includes="*.jar" /> </classpath> </javac> </target> Customization is very difficult
  • 8.
  • 9. Building Android applications The alternative Based on Maven → Maven plugin Allows for dependency management A lot more flexible → But still far from being perfect Real unit tests are possible Still using a test project for instrumentation tests
  • 10. The POM file <?xml version="1.0" encoding="UTF-8"?> <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.tngtech.internal.android</groupId> <artifactId>android-demo</artifactId> <version>1.0-SNAPSHOT</version> <packaging>apk</packaging> <dependencies> <dependency> <groupId>com.google.android</groupId> <artifactId>android</artifactId> <version>${platform.version}</version> <scope>provided</scope> </dependency> </dependencies> <build> <plugins> <plugin> <groupId>com.jayway.maven.plugins.android.generation2</groupId> <artifactId>android-maven-plugin</artifactId> <version>3.7.0</version> <configuration> <androidManifestFile>${project.basedir}/AndroidManifest.xml</androidManifestFile> <assetsDirectory>${project.basedir}/assets</assetsDirectory> <resourceDirectory>${project.basedir}/res</resourceDirectory> <sdk><platform>18</platform></sdk> </configuration> </plugin> </plugins> </build> </project>
  • 11. Building Android applications The new way Based on Gradle → Gradle-Plugin Built-in dependency management Using common Java patterns → But flexible enough to change that Real unit tests through plugins Instrumentation tests within the same project
  • 12. The Gradle build file buildscript { repositories { mavenCentral() } dependencies { classpath 'com.android.tools.build:gradle:0.6.+' } } apply plugin: 'android' repositories { mavenCentral() } dependencies { // Put all dependencies here } android { compileSdkVersion 18 buildToolsVersion "18.1.1" defaultConfig { minSdkVersion 18 targetSdkVersion 18 } }
  • 14. Android Studio The facts Based on IntelliJ Ready to use No additional plugins needed Brings shortcuts for AVD and SDK manager Out of the box support for the new build system Possibility to migrate old projects
  • 15.
  • 16. Overview A short introduction New Android build system Roboguice Robolectric
  • 17. What the heck is Roboguice? A dependency injection container An implementation of JSR 330 A fork of the Guice framework for the JDK Easy to configure and to use
  • 18. Dependency injection Instead of taking public class MainActivity extends Activity{ private LocationManager locationManager; public void onCreate(Bundle savedInstance) { // ... locationManager = (LocationManager) getSystemService(Activity.LOCATION_SERVICE); } } be given public class MainActivity extends RoboActivity{ @Inject private LocationManager locationManager; public void onCreate(Bundle savedInstance) { // ... } }
  • 19. Principles of DI Don't let a class create objects on its own Instead, pass them the objects they need Then you can exchange them for test purposes You can pass in test doubles But you can also exchange the "real" object easily Loose coupling becomes a reality
  • 20. How can you inject objects? Through the constructor: @Inject public MainActivity(LocationManager locationManager) { // ... this.locationManager = locationManager; } Into the field itself: @Inject private LocationManager locationManager; Into a property: @Inject public void setLocationManager(LocationManager locationManager) { this.locationManager = locationManager; }
  • 21. What can be injected? Arbitrary objects with a zero-arg constructor Objects with a constructor managed by Roboguice Views: @InjectView(R.id.specialButton) private Button button; Resources: @InjectResource(R.drawable.specialPicture) private Drawable picture; A lot of standard Android objects: LocationManager, AssetManager, ... AlarmManager, NotificationManager, ... Vibrator
  • 22. Robo* classes For DI to work, you have to extend the robo classes: Use them instead of the standard Android classes RoboActivity instead of Activity RoboListActivity instead of ListActivity RoboService instead of Service RoboFragment instead of Fragment ...
  • 23. Injecting providers: Sometimes, you need more than one object of a class public class SomeObjectProvider implements Provider<SomeObject> { @Inject private SomeOtherObject someOtherObject; @Override public SomeObject get() { return new SomeObject(someOtherObject); } } private class SomeObjectUser { @Inject private Provider<SomeObject> someObjectProvider; private SomeObject getObject() { return someObjectProvider.get(); } }
  • 24. Injecting injectors You can also inject an injector Then, you can get arbitrary objects out of the injector @Inject private Injector injector; public <T> T giveMeAnObjectOf(Class<T> clazz) { return injector.getInstance(clazz); }
  • 25.
  • 26. Configuration By defining a module, you can configure the objects injected public class SomeModule extends AbstractModule { @Override public void configure() { // Bind an interface to a specific class bind(SomeInterface.class).to(SomeImplementation.class); // Bind a standard provider to the class bind(SomeClass.class).toProvider(SomeClassProvider.class); } } Modules are discovered via "roboguice_modules.xml" <?xml version="1.0" encoding="utf-8"?> <resources> <string-array name="roboguice_modules"> <item>com.mypackage.SomeModule</item> </string-array> </resources>
  • 27. Integrate Roboguice (1) Add roboguice to the compile dependencies: // build.gradle dependencies { // ... compile 'roboguice:roboguice:2.+' } Extend the Robo* classes in your objects: public class SomeActivity extends RoboActivity { // ... } Inject your dependencies: @Inject private SomeObject someObject;
  • 28. Integrate Roboguice (2) Configure the module: public class SomeModule extends AbstractModule { @Override protected void configure() { bind(SomeClass.class).toProvider(SomeClassProvider.class); // ... } } Register the module: <?xml version="1.0" encoding="utf-8"?> <resources> <string-array name="roboguice_modules"> <item>com.mypackage.SomeModule</item> </string-array> </resources> Write unit tests: public class SomeActivityTest { // How to do that? }
  • 29. Overview A short introduction New Android build system Roboguice Robolectric
  • 30. Android testing in new build system Based on JUnit3 Requires separate test project Requires emulator or device for execution Lacks real mocking But initial support for some frameworks
  • 31.
  • 32. Can I run tests locally? No. It's impossible! Any method of the SDK will throw the following exception when called: java.lang.RuntimeException: Stub! at android.* Why is that? Android SDK jars for development only contain method stubs Is there a solution? Yes! Use Robolectric
  • 33. What the heck is Robolectric? Android SDK wrapper/enabler for local test execution Just another dependency of your project Sometimes dependency order is important Uses some magic to enable use of the stubbed SDK jars Unfortunately not yet complete
  • 34. What do I get? Tests are running on the dev machine Current version of JUnit 4 is used Any Mock- or Match-Framework can be used Can be used in parallel with instrumentation tests
  • 35. How do I enable Robolectric? buildscript { repositories { mavenCentral() } dependencies { classpath 'com.android.tools.build:gradle:0.6.+' classpath 'com.squareup.gradle:gradle-android-test-plugin:0.9.+' } } apply plugin: 'android' apply plugin: 'android-test' ...
  • 36. How do I implement a test? Just use the RobolectricTestRunner @RunWith(RobolectricTestRunner.class) class SomeActivityTest { @Before public void setUp() { // Preparation for every test } @Test public void testSomething() { // Your test code belongs here assertThat(1, is(not(2)); } }
  • 37. Basic concepts Shadows TextView textView = (TextView) mainActivity.findViewById(R.id.helloWorld); final ShadowTextView shadowTextView = Robolectric.shadowOf(textView); assertThat(shadowTextView.innerText(), is("Hello World!")); Implementation in Robolectric @Implements(TextView.class) public class ShadowTextView extends ShadowView { @RealObject TextView realTextView; @Override public String innerText() { CharSequence text = realTextView.getText(); return (text == null || realTextView.getVisibility() != View.VISIBLE) ? "" : text.toString(); } @Implementation public void setPaintFlags(int paintFlags) { this.paintFlags = paintFlags; } }
  • 38. Basic concepts Robolectric builds up a full application context Activities can be built activity = Robolectric.buildActivity(MainActivity.class).create().get(); Testing resource access is possible as well Resources resources = Robolectric.application.getResources(); assertThat(resources.getColor(R.color.Red), is(0xffff0000)); Modify preferences for tests SharedPreferences defaultSharedPreferences = ShadowPreferenceManager.getDefaultSharedPreferences( Robolectric.application); defaultSharedPreferences.edit() .putBoolean("test", true).putFloat("limit", 1.0f).apply();
  • 39. But ... Android Studio integration is not yet available Tests can be run via gradle task 'test' > gradle test IDE support only through ugly hacks
  • 40. Summary The new build system is a lot more flexible than the old one Android Studio is a cool new tool for app development It comes bundled with the SDK, you can start development immediately But there are still some issues with it Roboguice makes it possbible to decouple your application Robolectric can be used for local test execution
  • 41.
  • 42. Thank you! Are there any questions? andreas.wuerl@tngtech.com, thomas.endres@tngtech.com