SlideShare uma empresa Scribd logo
1 de 47
Baixar para ler offline
Android Unit Test Framework
http://pivotal.github.com/robolectric
Follow us on twitter: @robolectric
Wednesday, October 27, 2010
Tyler Schultz
Agile Engineer, Pivotal Labs
Wednesday, October 27, 2010
Talking Points
• Testing Approaches and Alternatives
• How Robolectric works
• How to extend Robolectric
• Workshop - write tests & help getting you
setup
Wednesday, October 27, 2010
Pivotal Labs
• Jasmine - Javascript BDD test framework,
@jasminebdd
• Cedar - iOS/Objective-C BDD test
framework, @cedarbdd
• Pivotal Tracker - www.pivotaltracker.com
You may have heard of us:
Wednesday, October 27, 2010
Why Unit Test?
Wednesday, October 27, 2010
Pivotal Labs
• www.pivotallabs.com
• San Francisco (Headquarters), NewYork,
Boulder, Singapore
• Primarily Rails - we do mobile too!
• Agile, XP, Continuos Integration, Pair
Programming
Wednesday, October 27, 2010
java.lang.RuntimeException(“Stub!”)
Wednesday, October 27, 2010
Google has stripped the classes in the android.jar file and
have had all their method bodies replaced with:
throw new RuntimeException(“Stub!”);
Wednesday, October 27, 2010
Additional Android testing challenges
• Many of the classes and methods are final
• Lack of interfaces
• Non public constructors
• static methods
Wednesday, October 27, 2010
sfandroid.org members, what have you
been doing?
Wednesday, October 27, 2010
Android Testing
Approaches
Wednesday, October 27, 2010
Android Testing
Approaches
• No Tests! EGAD!
• Android InstrumentationTests/Robotium -
integration style testing of Android apps
• Library of tested POJO’s, referenced from a
non tested Android project
• Mocking framework such as Easy Mock and
Mockito
Wednesday, October 27, 2010
Robolectric
Wednesday, October 27, 2010
Robolectric
• Christian Williams wrote the core while
working on projects at Xtreme Labs of
Toronto.ThankYou Xtreme Labs!
• Robolectric is published under the MIT
license
Wednesday, October 27, 2010
Robolectric
• Pivotal Labs has forked Xtreme Labs repo,
renamed it to Robolectric, and expanded its
functionality
• We’ve used Robolectric on several projects
with great success!
Wednesday, October 27, 2010
Robolectric
Why use Robolectric?
What makes it so great?
Wednesday, October 27, 2010
Why Use Robolectric
vs.Android Instrumentation Tests?
• Tests Run outside of the emulator in a JVM,
not the DalvikVM
- Running in a DalvikVM requires dexing,
packaging and installation on an emulator
or device - slow!
- Tests execute quickly in the JVM and
execute slowly on the emulator
Wednesday, October 27, 2010
Why Use Robolectric
vs.Android Instrumentation Tests?
• Iterate quickly!
• The latest Pivotal Android project is using
Robolectric boasting 1,047 tests that run in 28
seconds!
Wednesday, October 27, 2010
Why Use Robolectric
vs. POJO lib approach?
• The POJO lib approach leads to code
proliferation, interfaces with multiple
implementations - code bloat!
• Robolectric allows for vastly increased test
coverage. Test ALL your code, not just non-
Android code.
Wednesday, October 27, 2010
• Mocking frameworks can lead to tests that
are reverse implementation of the code
• Can lead to tests that are hard to read
• Can lead to tests that don’t help refactoring
Why use Robolectric
vs. Mock approach?
Wednesday, October 27, 2010
Why Use Robolectric?
• Iterate quickly
• Robolectric allows for a black box style of
testing
• Test behavior instead of implementation
• High test coverage
Wednesday, October 27, 2010
How does it work?
Google has stripped the classes in the android.jar file and
have had all their method bodies replaced with:
throw new RuntimeException(“Stub!”);
Wednesday, October 27, 2010
How does it work?
• Shadow Objects
• View and Resource Loading
Wednesday, October 27, 2010
How does it work?
• Robolectric intercepts the loading of Android classes
under test
• Rewrites the method bodies of Android classes (using
javassist)
• Binds new shadow objects to new Android objects
• The modified Android objects proxy method calls to
the shadow objects
Shadow objects
Wednesday, October 27, 2010
How does it work?
• Shadows back the Android classes. i.e.
ShadowImageView backs the ImageView class.
• Method calls to the Android object are proxied to the
shadow object’s method of the same signature, if it
exists.
• Simple implementations giving rudimentary behavior
• State is recorded so it can be verified in tests
Shadow objects
Wednesday, October 27, 2010
How does it work?
• Robolectric parses layout files and builds a
view object tree made of Android view
objects and, of course, their shadows.
• Some of the view xml attributes are applied
to the view object (currently applies: id,
visibility, enabled, text, checked, and src)
• Strings, string arrays, and color resources are
parsed loaded too.
View and Resource Loading
Wednesday, October 27, 2010
• RobolectricSample is a project that is setup
to use Robolectric
• http://github.com/pivotal/RobolectricSample
How can I get started?
Wednesday, October 27, 2010
Getting Started with
Robolectric
$ git clone git://github.com/pivotal/
RobolectricSample.git
$ cd RobolectricSample
$ git submodule update --init
$ android update project -p .
$ ant clean test
These commands are available on the
RobolectricSample README file
Wednesday, October 27, 2010
RobolectricSample
Ant Support
• RobolectricSample provides a build.xml file
which defines a test task
• Useful for Continuous Integration
Wednesday, October 27, 2010
Robolectric IDE
support
• RobolectricSample is setup with IntelliJ project
files. We’re using the latest IntelliJ EAP.
• Eclipse compatibility is currently unknown.
We need help from the community getting
Eclipse support!
• If nothing else, you should be able to use your
favorite tooling to write your code and use
the ant tasks to build and test.
Wednesday, October 27, 2010
RobolectricSample
Project Layout
• RobolectricSample - main Android module
• robolectric - module containing the robolectric
test framework (also a git submodule)
• aidl - module containing any aidl files your project
defines
• code - module where application code and tests go
Wednesday, October 27, 2010
Robolectric
Writing Tests
Wednesday, October 27, 2010
Writing Tests
...
@RunWith(RobolectricTestRunner.class)
public class MyActivityTest {
@Test
! public void shouldDoWizbangFooBar() {
...
Tests that reference Android need to be annotated:
Wednesday, October 27, 2010
Writing Tests
@Test
public void shouldShowLogoWhenButtonIsPressed() {
Activity activity = new MyActivity();
activity.onCreate(null);
ImageView logo = (ImageView) activity.findViewById(R.id.logo);
Button button = (Button) activity.findViewById(R.id.button);
assertThat(logo.getVisibility(), equalTo(View.GONE));
button.performClick();
assertThat(logo.getVisibility(), equalTo(View.VISIBLE));
}
Wednesday, October 27, 2010
Writing Tests
Dealing with cases where Android classes
do not provide a way to retrieve object state
Wednesday, October 27, 2010
Writing Tests
Accessing the Shadow Object
<ImageView
android:id=”@+id/logo”
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:src=”@drawable/logo” />
...
@Test
public void logoImageViewShouldUseTheLogoDrawable() {
ImageView logo = (ImageView) activity.findViewById(R.id.logo);
// imageView only provides logo.getDrawable();
ShadowImageView logoShadow = Robolectric.shadowOf(logo);
assertThat(logoShadow.resourceId, equalTo(R.drawable.logo));
}
Wednesday, October 27, 2010
Shadow Objects
• @RealObject
• __constructor__
• @Implements
• @Implementation
• Robolectric.bindAllShadowClasses()
Wednesday, October 27, 2010
Shadow Objects
@RealObject
• Robolectric is using reflection to
instantiate the shadow object (default or
no-args constructor)
• Robolectric will inject the Android object
onto shadow object’s fields annotated with
@RealObject
Wednesday, October 27, 2010
Shadow Objects
@RealObject
@Implements(View.class)
public class ShadowView {
@RealObject private View realView;
private int id;
...
Wednesday, October 27, 2010
Shadow Objects
• If no shadow class is registered for an
Android class, the Android object’s super
constructor will seek out a shadow class,
up through the constructor super chain
until one is found.
Wednesday, October 27, 2010
Shadow Objects
__constructor__
• When Robolectric is finished instantiating
the shadow object, it will attempt to invoke
a method on the shadow named
__constructor__ that has the same
args as the Android object’s constructor
Wednesday, October 27, 2010
Shadow Objects
__constructor__
public class Intent {
public Intent(String action, Uri uri) {
/* compiled code */
}
...
}
public class ShadowIntent {
public void __constructor__(String action,
Uri uri) {
...
}
...
}
Wednesday, October 27, 2010
Shadow Objects
@Implements
@Implements(View.class)
public class ShadowView {
@RealObject private View realView;
private int id;
...
Wednesday, October 27, 2010
Shadow Objects
@Implementation
public class ShadowTextView {
...
@Implementation
public CharSequence getText() {
return text;
}
...
Wednesday, October 27, 2010
Shadow Objects
Robolectric.bindAllShadowClasses()
• Where shadow objects are registered into
Robolectric
• This is a current listing of all the shadow objects
provided by Robolectric
Wednesday, October 27, 2010
Robolectric
Roadmap
• Eclipse support
• Simplified setup - robolectric.jar
• continued shadow updates and additions
• resource overrides, i.e. hdpi, landscape,
i18n, etc.
Wednesday, October 27, 2010
Q & A & Workshop!
• git clone git://github.com/pivotal/
RobolectricSample.git
• Mac users can download the latest IntelliJ EAP
from my machine: http://tschultz.local
• Add a button to the homepage of
RobolectricSample that toggles the visibility of the
robolectric logo. Tests First!
http://pivotal.github.com/robolectric
http://pivotal.github.com/RoblectricSample
twitter: @robolectric
Wednesday, October 27, 2010

Mais conteúdo relacionado

Mais procurados

Unit Testing Full@
Unit Testing Full@Unit Testing Full@
Unit Testing Full@
Alex Borsuk
 

Mais procurados (20)

Android Automation Using Robotium
Android Automation Using RobotiumAndroid Automation Using Robotium
Android Automation Using Robotium
 
Inside Android Testing
Inside Android TestingInside Android Testing
Inside Android Testing
 
Efficient JavaScript Unit Testing, JavaOne China 2013
Efficient JavaScript Unit Testing, JavaOne China 2013Efficient JavaScript Unit Testing, JavaOne China 2013
Efficient JavaScript Unit Testing, JavaOne China 2013
 
Android Testing: An Overview
Android Testing: An OverviewAndroid Testing: An Overview
Android Testing: An Overview
 
Robotium - sampath
Robotium - sampathRobotium - sampath
Robotium - sampath
 
Efficient JavaScript Unit Testing, May 2012
Efficient JavaScript Unit Testing, May 2012Efficient JavaScript Unit Testing, May 2012
Efficient JavaScript Unit Testing, May 2012
 
[AnDevCon 2016] Mutation Testing for Android
[AnDevCon 2016] Mutation Testing for Android[AnDevCon 2016] Mutation Testing for Android
[AnDevCon 2016] Mutation Testing for Android
 
Selenium Automation Testing Interview Questions And Answers
Selenium Automation Testing Interview Questions And AnswersSelenium Automation Testing Interview Questions And Answers
Selenium Automation Testing Interview Questions And Answers
 
Android with dagger_2
Android with dagger_2Android with dagger_2
Android with dagger_2
 
Android Test Driven Development
Android Test Driven DevelopmentAndroid Test Driven Development
Android Test Driven Development
 
Introduction to Protractor - Habilelabs
Introduction to Protractor - HabilelabsIntroduction to Protractor - Habilelabs
Introduction to Protractor - Habilelabs
 
Reliable mobile test automation
Reliable mobile test automationReliable mobile test automation
Reliable mobile test automation
 
Unit Testing Full@
Unit Testing Full@Unit Testing Full@
Unit Testing Full@
 
TDD with Visual Studio 2010
TDD with Visual Studio 2010TDD with Visual Studio 2010
TDD with Visual Studio 2010
 
Top trending selenium interview questions
Top trending selenium interview questionsTop trending selenium interview questions
Top trending selenium interview questions
 
Implementing Quality on a Java Project
Implementing Quality on a Java ProjectImplementing Quality on a Java Project
Implementing Quality on a Java Project
 
Principles and patterns for test driven development
Principles and patterns for test driven developmentPrinciples and patterns for test driven development
Principles and patterns for test driven development
 
Efficient JavaScript Unit Testing, March 2013
Efficient JavaScript Unit Testing, March 2013Efficient JavaScript Unit Testing, March 2013
Efficient JavaScript Unit Testing, March 2013
 
Android Test Pyramid - Ágiles 2013
Android Test Pyramid - Ágiles 2013Android Test Pyramid - Ágiles 2013
Android Test Pyramid - Ágiles 2013
 
Oh so you test? - A guide to testing on Android from Unit to Mutation
Oh so you test? - A guide to testing on Android from Unit to MutationOh so you test? - A guide to testing on Android from Unit to Mutation
Oh so you test? - A guide to testing on Android from Unit to Mutation
 

Semelhante a Learn How to Unit Test Your Android Application (with Robolectric)

Csc253 chapter 09
Csc253 chapter 09Csc253 chapter 09
Csc253 chapter 09
PCC
 
Introduction to Robotium
Introduction to RobotiumIntroduction to Robotium
Introduction to Robotium
alii abbb
 

Semelhante a Learn How to Unit Test Your Android Application (with Robolectric) (20)

Robolectric Adventure
Robolectric AdventureRobolectric Adventure
Robolectric Adventure
 
The Cowardly Test-o-Phobe's Guide To Testing
The Cowardly Test-o-Phobe's Guide To TestingThe Cowardly Test-o-Phobe's Guide To Testing
The Cowardly Test-o-Phobe's Guide To Testing
 
Effective .NET Core Unit Testing with SQLite and Dapper
Effective .NET Core Unit Testing with SQLite and DapperEffective .NET Core Unit Testing with SQLite and Dapper
Effective .NET Core Unit Testing with SQLite and Dapper
 
Chegg - iOS @ Scale
Chegg - iOS @ ScaleChegg - iOS @ Scale
Chegg - iOS @ Scale
 
Effective .NET Core Unit Testing with SQLite and Dapper
Effective .NET Core Unit Testing with SQLite and DapperEffective .NET Core Unit Testing with SQLite and Dapper
Effective .NET Core Unit Testing with SQLite and Dapper
 
Robotium framework & Jenkins CI tools - TdT@Cluj #19
Robotium framework & Jenkins CI tools - TdT@Cluj #19Robotium framework & Jenkins CI tools - TdT@Cluj #19
Robotium framework & Jenkins CI tools - TdT@Cluj #19
 
Csc253 chapter 09
Csc253 chapter 09Csc253 chapter 09
Csc253 chapter 09
 
Feature Bits at LSSC10
Feature  Bits at LSSC10Feature  Bits at LSSC10
Feature Bits at LSSC10
 
[React-Native Tutorial 10] Camera Roll / Gallery / Camera / Native Modules by...
[React-Native Tutorial 10] Camera Roll / Gallery / Camera / Native Modules by...[React-Native Tutorial 10] Camera Roll / Gallery / Camera / Native Modules by...
[React-Native Tutorial 10] Camera Roll / Gallery / Camera / Native Modules by...
 
Protractor survival guide
Protractor survival guideProtractor survival guide
Protractor survival guide
 
jDays Sweden 2016
jDays Sweden 2016jDays Sweden 2016
jDays Sweden 2016
 
Cloud-ready Micro Java EE 8
Cloud-ready Micro Java EE 8Cloud-ready Micro Java EE 8
Cloud-ready Micro Java EE 8
 
MVC and Entity Framework 4
MVC and Entity Framework 4MVC and Entity Framework 4
MVC and Entity Framework 4
 
[Ultracode Munich #4] Short introduction to the new Android build system incl...
[Ultracode Munich #4] Short introduction to the new Android build system incl...[Ultracode Munich #4] Short introduction to the new Android build system incl...
[Ultracode Munich #4] Short introduction to the new Android build system incl...
 
Oscon 2010
Oscon 2010Oscon 2010
Oscon 2010
 
Java EE changes design pattern implementation: JavaDays Kiev 2015
Java EE changes design pattern implementation: JavaDays Kiev 2015Java EE changes design pattern implementation: JavaDays Kiev 2015
Java EE changes design pattern implementation: JavaDays Kiev 2015
 
Guide to the jungle of testing frameworks
Guide to the jungle of testing frameworksGuide to the jungle of testing frameworks
Guide to the jungle of testing frameworks
 
Introduction to Robotium
Introduction to RobotiumIntroduction to Robotium
Introduction to Robotium
 
Devday2016 real unittestingwithmockframework-phatvu
Devday2016 real unittestingwithmockframework-phatvuDevday2016 real unittestingwithmockframework-phatvu
Devday2016 real unittestingwithmockframework-phatvu
 
springtraning-7024840-phpapp01.pdf
springtraning-7024840-phpapp01.pdfspringtraning-7024840-phpapp01.pdf
springtraning-7024840-phpapp01.pdf
 

Mais de Marakana Inc.

Behavior Driven Development
Behavior Driven DevelopmentBehavior Driven Development
Behavior Driven Development
Marakana Inc.
 
Why Java Needs Hierarchical Data
Why Java Needs Hierarchical DataWhy Java Needs Hierarchical Data
Why Java Needs Hierarchical Data
Marakana Inc.
 
Pictures from "Learn about RenderScript" meetup at SF Android User Group
Pictures from "Learn about RenderScript" meetup at SF Android User GroupPictures from "Learn about RenderScript" meetup at SF Android User Group
Pictures from "Learn about RenderScript" meetup at SF Android User Group
Marakana Inc.
 
2010 07-18.wa.rails tdd-6
2010 07-18.wa.rails tdd-62010 07-18.wa.rails tdd-6
2010 07-18.wa.rails tdd-6
Marakana Inc.
 
Graphicsand animations devoxx2010 (1)
Graphicsand animations devoxx2010 (1)Graphicsand animations devoxx2010 (1)
Graphicsand animations devoxx2010 (1)
Marakana Inc.
 

Mais de Marakana Inc. (20)

Android Services Black Magic by Aleksandar Gargenta
Android Services Black Magic by Aleksandar GargentaAndroid Services Black Magic by Aleksandar Gargenta
Android Services Black Magic by Aleksandar Gargenta
 
JRuby at Square
JRuby at SquareJRuby at Square
JRuby at Square
 
Behavior Driven Development
Behavior Driven DevelopmentBehavior Driven Development
Behavior Driven Development
 
Martin Odersky: What's next for Scala
Martin Odersky: What's next for ScalaMartin Odersky: What's next for Scala
Martin Odersky: What's next for Scala
 
Why Java Needs Hierarchical Data
Why Java Needs Hierarchical DataWhy Java Needs Hierarchical Data
Why Java Needs Hierarchical Data
 
Deep Dive Into Android Security
Deep Dive Into Android SecurityDeep Dive Into Android Security
Deep Dive Into Android Security
 
Securing Android
Securing AndroidSecuring Android
Securing Android
 
Pictures from "Learn about RenderScript" meetup at SF Android User Group
Pictures from "Learn about RenderScript" meetup at SF Android User GroupPictures from "Learn about RenderScript" meetup at SF Android User Group
Pictures from "Learn about RenderScript" meetup at SF Android User Group
 
Android UI Tips, Tricks and Techniques
Android UI Tips, Tricks and TechniquesAndroid UI Tips, Tricks and Techniques
Android UI Tips, Tricks and Techniques
 
2010 07-18.wa.rails tdd-6
2010 07-18.wa.rails tdd-62010 07-18.wa.rails tdd-6
2010 07-18.wa.rails tdd-6
 
Efficient Rails Test-Driven Development - Week 6
Efficient Rails Test-Driven Development - Week 6Efficient Rails Test-Driven Development - Week 6
Efficient Rails Test-Driven Development - Week 6
 
Graphicsand animations devoxx2010 (1)
Graphicsand animations devoxx2010 (1)Graphicsand animations devoxx2010 (1)
Graphicsand animations devoxx2010 (1)
 
What's this jQuery? Where it came from, and how it will drive innovation
What's this jQuery? Where it came from, and how it will drive innovationWhat's this jQuery? Where it came from, and how it will drive innovation
What's this jQuery? Where it came from, and how it will drive innovation
 
jQuery State of the Union - Yehuda Katz
jQuery State of the Union - Yehuda KatzjQuery State of the Union - Yehuda Katz
jQuery State of the Union - Yehuda Katz
 
Pics from: "James Gosling on Apple, Apache, Google, Oracle and the Future of ...
Pics from: "James Gosling on Apple, Apache, Google, Oracle and the Future of ...Pics from: "James Gosling on Apple, Apache, Google, Oracle and the Future of ...
Pics from: "James Gosling on Apple, Apache, Google, Oracle and the Future of ...
 
Efficient Rails Test Driven Development (class 4) by Wolfram Arnold
Efficient Rails Test Driven Development (class 4) by Wolfram ArnoldEfficient Rails Test Driven Development (class 4) by Wolfram Arnold
Efficient Rails Test Driven Development (class 4) by Wolfram Arnold
 
Efficient Rails Test Driven Development (class 3) by Wolfram Arnold
Efficient Rails Test Driven Development (class 3) by Wolfram ArnoldEfficient Rails Test Driven Development (class 3) by Wolfram Arnold
Efficient Rails Test Driven Development (class 3) by Wolfram Arnold
 
Learn about JRuby Internals from one of the JRuby Lead Developers, Thomas Enebo
Learn about JRuby Internals from one of the JRuby Lead Developers, Thomas EneboLearn about JRuby Internals from one of the JRuby Lead Developers, Thomas Enebo
Learn about JRuby Internals from one of the JRuby Lead Developers, Thomas Enebo
 
Replacing Java Incrementally
Replacing Java IncrementallyReplacing Java Incrementally
Replacing Java Incrementally
 
Learn to Build like you Code with Apache Buildr
Learn to Build like you Code with Apache BuildrLearn to Build like you Code with Apache Buildr
Learn to Build like you Code with Apache Buildr
 

Último

IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
Enterprise Knowledge
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
vu2urc
 

Último (20)

Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
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
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
Tech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdfTech Trends Report 2024 Future Today Institute.pdf
Tech Trends Report 2024 Future Today Institute.pdf
 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
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
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
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
 
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
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
Histor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slideHistor y of HAM Radio presentation slide
Histor y of HAM Radio presentation slide
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Evaluating the top large language models.pdf
Evaluating the top large language models.pdfEvaluating the top large language models.pdf
Evaluating the top large language models.pdf
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 

Learn How to Unit Test Your Android Application (with Robolectric)

  • 1. Android Unit Test Framework http://pivotal.github.com/robolectric Follow us on twitter: @robolectric Wednesday, October 27, 2010
  • 2. Tyler Schultz Agile Engineer, Pivotal Labs Wednesday, October 27, 2010
  • 3. Talking Points • Testing Approaches and Alternatives • How Robolectric works • How to extend Robolectric • Workshop - write tests & help getting you setup Wednesday, October 27, 2010
  • 4. Pivotal Labs • Jasmine - Javascript BDD test framework, @jasminebdd • Cedar - iOS/Objective-C BDD test framework, @cedarbdd • Pivotal Tracker - www.pivotaltracker.com You may have heard of us: Wednesday, October 27, 2010
  • 5. Why Unit Test? Wednesday, October 27, 2010
  • 6. Pivotal Labs • www.pivotallabs.com • San Francisco (Headquarters), NewYork, Boulder, Singapore • Primarily Rails - we do mobile too! • Agile, XP, Continuos Integration, Pair Programming Wednesday, October 27, 2010
  • 8. Google has stripped the classes in the android.jar file and have had all their method bodies replaced with: throw new RuntimeException(“Stub!”); Wednesday, October 27, 2010
  • 9. Additional Android testing challenges • Many of the classes and methods are final • Lack of interfaces • Non public constructors • static methods Wednesday, October 27, 2010
  • 10. sfandroid.org members, what have you been doing? Wednesday, October 27, 2010
  • 12. Android Testing Approaches • No Tests! EGAD! • Android InstrumentationTests/Robotium - integration style testing of Android apps • Library of tested POJO’s, referenced from a non tested Android project • Mocking framework such as Easy Mock and Mockito Wednesday, October 27, 2010
  • 14. Robolectric • Christian Williams wrote the core while working on projects at Xtreme Labs of Toronto.ThankYou Xtreme Labs! • Robolectric is published under the MIT license Wednesday, October 27, 2010
  • 15. Robolectric • Pivotal Labs has forked Xtreme Labs repo, renamed it to Robolectric, and expanded its functionality • We’ve used Robolectric on several projects with great success! Wednesday, October 27, 2010
  • 16. Robolectric Why use Robolectric? What makes it so great? Wednesday, October 27, 2010
  • 17. Why Use Robolectric vs.Android Instrumentation Tests? • Tests Run outside of the emulator in a JVM, not the DalvikVM - Running in a DalvikVM requires dexing, packaging and installation on an emulator or device - slow! - Tests execute quickly in the JVM and execute slowly on the emulator Wednesday, October 27, 2010
  • 18. Why Use Robolectric vs.Android Instrumentation Tests? • Iterate quickly! • The latest Pivotal Android project is using Robolectric boasting 1,047 tests that run in 28 seconds! Wednesday, October 27, 2010
  • 19. Why Use Robolectric vs. POJO lib approach? • The POJO lib approach leads to code proliferation, interfaces with multiple implementations - code bloat! • Robolectric allows for vastly increased test coverage. Test ALL your code, not just non- Android code. Wednesday, October 27, 2010
  • 20. • Mocking frameworks can lead to tests that are reverse implementation of the code • Can lead to tests that are hard to read • Can lead to tests that don’t help refactoring Why use Robolectric vs. Mock approach? Wednesday, October 27, 2010
  • 21. Why Use Robolectric? • Iterate quickly • Robolectric allows for a black box style of testing • Test behavior instead of implementation • High test coverage Wednesday, October 27, 2010
  • 22. How does it work? Google has stripped the classes in the android.jar file and have had all their method bodies replaced with: throw new RuntimeException(“Stub!”); Wednesday, October 27, 2010
  • 23. How does it work? • Shadow Objects • View and Resource Loading Wednesday, October 27, 2010
  • 24. How does it work? • Robolectric intercepts the loading of Android classes under test • Rewrites the method bodies of Android classes (using javassist) • Binds new shadow objects to new Android objects • The modified Android objects proxy method calls to the shadow objects Shadow objects Wednesday, October 27, 2010
  • 25. How does it work? • Shadows back the Android classes. i.e. ShadowImageView backs the ImageView class. • Method calls to the Android object are proxied to the shadow object’s method of the same signature, if it exists. • Simple implementations giving rudimentary behavior • State is recorded so it can be verified in tests Shadow objects Wednesday, October 27, 2010
  • 26. How does it work? • Robolectric parses layout files and builds a view object tree made of Android view objects and, of course, their shadows. • Some of the view xml attributes are applied to the view object (currently applies: id, visibility, enabled, text, checked, and src) • Strings, string arrays, and color resources are parsed loaded too. View and Resource Loading Wednesday, October 27, 2010
  • 27. • RobolectricSample is a project that is setup to use Robolectric • http://github.com/pivotal/RobolectricSample How can I get started? Wednesday, October 27, 2010
  • 28. Getting Started with Robolectric $ git clone git://github.com/pivotal/ RobolectricSample.git $ cd RobolectricSample $ git submodule update --init $ android update project -p . $ ant clean test These commands are available on the RobolectricSample README file Wednesday, October 27, 2010
  • 29. RobolectricSample Ant Support • RobolectricSample provides a build.xml file which defines a test task • Useful for Continuous Integration Wednesday, October 27, 2010
  • 30. Robolectric IDE support • RobolectricSample is setup with IntelliJ project files. We’re using the latest IntelliJ EAP. • Eclipse compatibility is currently unknown. We need help from the community getting Eclipse support! • If nothing else, you should be able to use your favorite tooling to write your code and use the ant tasks to build and test. Wednesday, October 27, 2010
  • 31. RobolectricSample Project Layout • RobolectricSample - main Android module • robolectric - module containing the robolectric test framework (also a git submodule) • aidl - module containing any aidl files your project defines • code - module where application code and tests go Wednesday, October 27, 2010
  • 33. Writing Tests ... @RunWith(RobolectricTestRunner.class) public class MyActivityTest { @Test ! public void shouldDoWizbangFooBar() { ... Tests that reference Android need to be annotated: Wednesday, October 27, 2010
  • 34. Writing Tests @Test public void shouldShowLogoWhenButtonIsPressed() { Activity activity = new MyActivity(); activity.onCreate(null); ImageView logo = (ImageView) activity.findViewById(R.id.logo); Button button = (Button) activity.findViewById(R.id.button); assertThat(logo.getVisibility(), equalTo(View.GONE)); button.performClick(); assertThat(logo.getVisibility(), equalTo(View.VISIBLE)); } Wednesday, October 27, 2010
  • 35. Writing Tests Dealing with cases where Android classes do not provide a way to retrieve object state Wednesday, October 27, 2010
  • 36. Writing Tests Accessing the Shadow Object <ImageView android:id=”@+id/logo” android:layout_width=”wrap_content” android:layout_height=”wrap_content” android:src=”@drawable/logo” /> ... @Test public void logoImageViewShouldUseTheLogoDrawable() { ImageView logo = (ImageView) activity.findViewById(R.id.logo); // imageView only provides logo.getDrawable(); ShadowImageView logoShadow = Robolectric.shadowOf(logo); assertThat(logoShadow.resourceId, equalTo(R.drawable.logo)); } Wednesday, October 27, 2010
  • 37. Shadow Objects • @RealObject • __constructor__ • @Implements • @Implementation • Robolectric.bindAllShadowClasses() Wednesday, October 27, 2010
  • 38. Shadow Objects @RealObject • Robolectric is using reflection to instantiate the shadow object (default or no-args constructor) • Robolectric will inject the Android object onto shadow object’s fields annotated with @RealObject Wednesday, October 27, 2010
  • 39. Shadow Objects @RealObject @Implements(View.class) public class ShadowView { @RealObject private View realView; private int id; ... Wednesday, October 27, 2010
  • 40. Shadow Objects • If no shadow class is registered for an Android class, the Android object’s super constructor will seek out a shadow class, up through the constructor super chain until one is found. Wednesday, October 27, 2010
  • 41. Shadow Objects __constructor__ • When Robolectric is finished instantiating the shadow object, it will attempt to invoke a method on the shadow named __constructor__ that has the same args as the Android object’s constructor Wednesday, October 27, 2010
  • 42. Shadow Objects __constructor__ public class Intent { public Intent(String action, Uri uri) { /* compiled code */ } ... } public class ShadowIntent { public void __constructor__(String action, Uri uri) { ... } ... } Wednesday, October 27, 2010
  • 43. Shadow Objects @Implements @Implements(View.class) public class ShadowView { @RealObject private View realView; private int id; ... Wednesday, October 27, 2010
  • 44. Shadow Objects @Implementation public class ShadowTextView { ... @Implementation public CharSequence getText() { return text; } ... Wednesday, October 27, 2010
  • 45. Shadow Objects Robolectric.bindAllShadowClasses() • Where shadow objects are registered into Robolectric • This is a current listing of all the shadow objects provided by Robolectric Wednesday, October 27, 2010
  • 46. Robolectric Roadmap • Eclipse support • Simplified setup - robolectric.jar • continued shadow updates and additions • resource overrides, i.e. hdpi, landscape, i18n, etc. Wednesday, October 27, 2010
  • 47. Q & A & Workshop! • git clone git://github.com/pivotal/ RobolectricSample.git • Mac users can download the latest IntelliJ EAP from my machine: http://tschultz.local • Add a button to the homepage of RobolectricSample that toggles the visibility of the robolectric logo. Tests First! http://pivotal.github.com/robolectric http://pivotal.github.com/RoblectricSample twitter: @robolectric Wednesday, October 27, 2010