SlideShare a Scribd company logo
We're an independent
design & development
agency.
Testing your Android
application
IVAN KUŠT
ROBOLECTRIC
ROBOLECTRIC
• http://robolectric.org/
• unit test framework
• tests run in JVM on your machine
ROBOLECTRIC SETUP
• 1. add gradle dependencies
• 2. write test application class
• 3. write test class
• 4. run tests
1. ADD GRADLE DEPENDENCIES
• make sure “Unit tests” is selected as Test Artifact under
Build Variants
• add the robolectric dependency in your app build.gradle file:

testCompile 'junit:junit:4.12'

testCompile 'org.hamcrest:hamcrest-library:1.3'


testCompile 'org.robolectric:robolectric:3.0'

testCompile 'org.robolectric:shadows-support-v4:3.0'
2. WRITE TEST APPLICATION CLASS
• all unit test code goes into test flavour
• Test{applicationName}
• must extend application class
• runs instead of application class in tests
• should inject test dependencies
3. WRITE TEST CLASS
• create new class in test flavor
• specify runner with @RunWith annotation
• add @Config annotation
• add test methods and annotate them with @Test
TEST CONFIGURATION
• constants property of @Config annotation is mandatory
• for all other options check:

http://robolectric.org/configuring/
@RunWith(RobolectricGradleTestRunner.class)

@Config(constants = BuildConfig.class, sdk = 21)

public class DeckardActivityTest {



@Test 

public void testSomething() throws Exception { 

assertTrue(Robolectric.setupActivity(DeckardActivity.class) != null);

}

}
4. RUN TESTS
• from Android studio
• ./gradlew clean test
MOCK WEB SERVER
MOCK WEB SERVER
• network responses should be mocked in unit tests
• speed
• consistency
GRADLE DEPENDENCIES
• add the MockWebServer dependency in your app
build.gradle file:


• MockWebServer depends on okhttp library
• make sure that mockwebserver version matches okhttp
version
testCompile 'com.squareup.okhttp:mockwebserver:2.7.4'
USAGE
• 1. instantiate MockWebServer
• 2. call start() method
• 3. get local server url by calling url(“/“)
• 4. inject server local url into networking module
• 5. enqueue responses using enqueue() method
USAGE
• in both unit and instrumentation tests (steps 1 - 4):
• prepare and inject MockWebServer in @Before method
(called before every @Test method)
• stop MockWebServer in @After method (called after
every @Test method)
USAGE
• or in Robolectric unit tests (steps 1 - 4):
• prepare and inject MockWebServer in:

beforeTest(Method) method in Test application
• stop MockWebServer in:

afterTest(Method method) in Test application
ENQUEUEING RESPONSES
• enqueue(), MockResponse object
• https://github.com/square/okhttp/blob/master/
mockwebserver/src/main/java/com/squareup/okhttp/
mockwebserver/MockResponse.java
mockWebServer.enqueue( 

new MockResponse()

.setResponseCode(200)

.setBody("Response body");

);
LARGE RESPONSES?
• 1. store response body content to a file
• 2. put the file inside /test/resources/ directory
• 3. read the contents of the file in test:
public static String readFromFile(String filename) {

InputStream is = ResourceUtils.class.getClassLoader().getResourceAsStream(filename);

return convertStreamToString(is);

}
CHECKING REQUESTS
• mockWebServer.getRequestCount()
• mockWebServer.takeRequest()
• mockWebServer.takeRequest(long, TimeUnit)
@Test 

public void nameOk() throws Exception {



PokemonTestApp.getMockWebServer().enqueue(



new MockResponse()

.setResponseCode(200)

.setBody(ResourceUtils.readFromFile("charizard.json"))

);





String resourceUri = "api/v1/pokemon/6/";

Pokemon pokemon = new Pokemon();

pokemon.setResourceUri(resourceUri);



Activity activity = buildActivity(pokemon);


RecordedRequest request = takeLastRequest();



//Perform the assertions



}
(A)SYNCHRONOUS EXECUTORS
• unit tests run in a single thread
• waiting for background threads complicates tests
• solution: Synchronous executors
(A)SYNCHRONOUS EXECUTORS
• setting executor on Retrofit: 



• specify executor for networking and for callback
• for tests: both synchronous
return new RestAdapter.Builder()
...

.setExecutors(new BackgroundExecutor(), new CallbackExecutor())
...

.build();
SYNCHRONOUS EXECUTOR?
• runs the queued runnable in the same thread
• simple as that:
public class SynchronousExecutor implements Executor {



@Override

public void execute(Runnable command) {

command.run();

}

}
SHADOW CLASSES
SHADOWING A CLASS
• 1. create a custom Robolectric runner
• 2. declare shadowed classes in createClassLoaderConfig()
method
• 3. implement shadow class
• 4. run tests with custom runner
public class CustomRobolectricGradleTestRunner extends RobolectricGradleTestRunner {



public CustomRobolectricGradleTestRunner(Class<?> klass) throws InitializationError {

super(klass);

}



@Override

protected AndroidManifest getAppManifest(Config config) {

AndroidManifest appManifest = super.getAppManifest(config);
// needs to be the java package, not applicationId

appManifest.setPackageName("co.infinum.app");



return appManifest;

}



@Override

public InstrumentationConfiguration createClassLoaderConfig() {

InstrumentationConfiguration.Builder builder =
InstrumentationConfiguration.newBuilder();



builder.addInstrumentedClass(ShadowOutline.class.getName());

builder.addInstrumentedClass(ShadowAlertDialogSupportV7.class.getName());

builder.addInstrumentedClass(ShadowSpinnerView.class.getName());

return builder.build();

}



}
3. IMPLEMENT SHADOW CLASS
• create a new class with @Implements(OriginalClass.class)
annotation
• add @Implementation annotation to methods that “override”
behaviour from original class
• you can leave some methods unchanged
• if you wish to use an instance of OriginalClass in your
shadow class it must be annotated with @RealObject
ADD SHADOWS TO TEST
• in order to make your shadows available in test add them to
@Config in your test:



@Config(shadows = {ShadowClass.class})
@Implements(Outline.class)

public class ShadowOutline {



@RealObject

private Outline outline;



public Path path;



public Rect rect;



public float radius;



public float alpha;



@Implementation

public void setConvexPath(Path convexPath) {

if (path == null) {

path = new Path();

}



path.set(convexPath);

}

}
ESPRESSO
SETUP
• 1. add gradle dependencies
• 2. specify runner
• 3. write test class
• 4. run
1. ADD DEPENDENCIES
• make sure “Android Instrumentation tests” is selected as Test
Artifact under Build Variants
• add the robolectric dependency in your app build.gradle file:
// Espresso



androidTestCompile 'com.android.support.test.espresso:espresso-core:2.2.1'

androidTestCompile 'com.android.support.test.espresso:espresso-intents:2.2.1'

androidTestCompile 'com.android.support.test:runner:0.4.1'

androidTestCompile 'com.android.support.test:rules:0.4.1'
2. SPECIFY RUNNER
• specify default instrumentation test runner in application
build.gradle:
android {
defaultConfig {
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
}
3. WRITE TEST CLASS
• create new class in test flavor
• annotate with @LargeTest
• add field of type ActivityTestRule and annotate with @Rule
- defines the activity that will run
• add test methods and annotate them with @Test
4. RUN
• from Android studio

• ./gradlew clean 

connectedAndroidTest
FEW MORE TIPS
ASSERTJ ANDROID
• https://github.com/square/assertj-android
• extension of AssertJ
• you can extend and set up your own
assertions
//Check that name in details is displayed properly.
assertThat(activity.findViewById(R.id.name).getVisibility())
.isEqualTo(View.VISIBLE);



assertThat(((TextView) activity.findViewById(R.id.name))

.getText()).isEqualTo("Charizard");
TEST REPORT
• will be generated in:

/app/build/reports/tests/{flavour}/index.html

• if tests faill, gradle will print out the location of the report in
console as well
LOGS
• to show Log.d() outputs add folloving in your @Before
method:



ShadowLog.stream = System.out;
USING MOCK WEB SERVER
• like in unit tests (steps 1 - 4):
• prepare and inject MockWebServer in @Before method
(called before every @Test method)
• stop MockWebServer in @After method (called after every
@Test method)
• note that in instrument tests there is no Test application that
you can use
RESOURCES
• http://robolectric.org/
• https://github.com/square/assertj-android
• http://www.vogella.com/tutorials/
AndroidTestingEspresso/article.html
• http://developer.android.com/training/testing/ui-
testing/espresso-testing.html
Thank you!
Visit www.infinum.co or find us on social networks:
infinum.co infinumco infinumco infinum

More Related Content

PDF
Android Meetup Slovenija #3 - Testing with Robolectric by Ivan Kust
PDF
Testing Spring MVC and REST Web Applications
PPT
Selenium-Browser-Based-Automated-Testing-for-Grails-Apps
PDF
Testing with Spring: An Introduction
PPT
Testing In Java
PPT
Automating Software Communications Architecture (SCA) Testing with Spectra CX
PDF
Testing Web Apps with Spring Framework
PDF
An Introduction to JUnit 5 and how to use it with Spring boot tests and Mockito
Android Meetup Slovenija #3 - Testing with Robolectric by Ivan Kust
Testing Spring MVC and REST Web Applications
Selenium-Browser-Based-Automated-Testing-for-Grails-Apps
Testing with Spring: An Introduction
Testing In Java
Automating Software Communications Architecture (SCA) Testing with Spectra CX
Testing Web Apps with Spring Framework
An Introduction to JUnit 5 and how to use it with Spring boot tests and Mockito

What's hot (20)

PDF
Apache maven, a software project management tool
PDF
Continuous delivery-with-maven
PDF
Testing with Spring 4.x
DOCX
Selenium notes
PDF
Pragmatic Java Test Automation
PDF
Testing Spring Boot Applications
PDF
Agile Open Source Performance Test Workshop for Developers, Testers, IT Ops
PDF
Selenium - Introduction
PPTX
Get the Most out of Testing with Spring 4.2
PDF
Alm 4 Azure
PDF
API Testing following the Test Pyramid
PDF
Eclipse IDE, 2019.09, Java Development
PPTX
Release With Maven
PDF
Selenium Handbook
PDF
Spring Framework 4.1
PDF
Open Source Software Testing Tools
PDF
Unit testing - A&BP CC
PDF
Selenium Tutorial
PDF
Testing Web Apps with Spring Framework 3.2
PDF
Lab 7b) test a web application
Apache maven, a software project management tool
Continuous delivery-with-maven
Testing with Spring 4.x
Selenium notes
Pragmatic Java Test Automation
Testing Spring Boot Applications
Agile Open Source Performance Test Workshop for Developers, Testers, IT Ops
Selenium - Introduction
Get the Most out of Testing with Spring 4.2
Alm 4 Azure
API Testing following the Test Pyramid
Eclipse IDE, 2019.09, Java Development
Release With Maven
Selenium Handbook
Spring Framework 4.1
Open Source Software Testing Tools
Unit testing - A&BP CC
Selenium Tutorial
Testing Web Apps with Spring Framework 3.2
Lab 7b) test a web application
Ad

Similar to Infinum Android Talks #17 - Testing your Android applications by Ivan Kust (20)

PDF
Guide to the jungle of testing frameworks
PDF
Apache DeltaSpike
PDF
Agile Swift
PDF
Javascript tdd byandreapaciolla
PPT
Stopping the Rot - Putting Legacy C++ Under Test
PPTX
JLove - Replicating production on your laptop using the magic of containers
PPTX
JBCN_Testing_With_Containers
PDF
Testing Your Application On Google App Engine
PDF
Testing your application on Google App Engine
PDF
Test Driven Development with JavaFX
PPTX
Unit tests and TDD
PPT
Maven basic concept
PPTX
Automated php unit testing in drupal 8
PDF
BMO - Intelligent Projects with Maven
PDF
Level Up Your Integration Testing With Testcontainers
PPTX
QA Fest 2018. Adam Stasiak. React Native is Coming – the story of hybrid mobi...
PPTX
JNation - Integration Testing from the Trenches Rebooted
PDF
Apache DeltaSpike the CDI toolbox
PDF
Apache DeltaSpike: The CDI Toolbox
Guide to the jungle of testing frameworks
Apache DeltaSpike
Agile Swift
Javascript tdd byandreapaciolla
Stopping the Rot - Putting Legacy C++ Under Test
JLove - Replicating production on your laptop using the magic of containers
JBCN_Testing_With_Containers
Testing Your Application On Google App Engine
Testing your application on Google App Engine
Test Driven Development with JavaFX
Unit tests and TDD
Maven basic concept
Automated php unit testing in drupal 8
BMO - Intelligent Projects with Maven
Level Up Your Integration Testing With Testcontainers
QA Fest 2018. Adam Stasiak. React Native is Coming – the story of hybrid mobi...
JNation - Integration Testing from the Trenches Rebooted
Apache DeltaSpike the CDI toolbox
Apache DeltaSpike: The CDI Toolbox
Ad

More from Infinum (20)

PDF
Infinum Android Talks #20 - Making your Android apps fast like Blue Runner an...
PDF
Infinum Android Talks #20 - DiffUtil
PDF
Infinum Android Talks #20 - Benefits of using Kotlin
PDF
Infinum iOS Talks #4 - Making our VIPER more reactive
PDF
Infinum iOS Talks #4 - Making your Swift networking code more awesome with Re...
PDF
Infinum Android Talks #13 - Using ViewDragHelper
PDF
Infinum Android Talks #14 - Log4j
PDF
Infinum Android Talks #9 - Making your app location-aware
PDF
Infinum Android Talks #14 - Gradle plugins
PDF
Infinum Android Talks #14 - Facebook for Android API
PDF
Infinum Android Talks #19 - Stop wasting time fixing bugs with TDD by Domagoj...
PDF
Infinum Android Talks #18 - Create fun lists by Ivan Marić
PDF
Infinum Android Talks #18 - In-app billing by Ivan Marić
PDF
Infinum Android Talks #18 - How to cache like a boss by Željko Plesac
PDF
Infinum iOS Talks #2 - VIPER for everybody by Damjan Vujaklija
PDF
Infinum iOS Talks #2 - Xamarin by Ivan Đikić
PDF
Infinum iOS Talks #1 - Swift under the hood: Method Dispatching by Vlaho Poluta
PDF
Infinum iOS Talks #1 - Swift done right by Ivan Dikic
PDF
Infinum iOS Talks #1 - Becoming an iOS developer swiftly by Vedran Burojevic
PDF
Infinum Android Talks #17 - A quest for WebSockets by Zeljko Plesac
Infinum Android Talks #20 - Making your Android apps fast like Blue Runner an...
Infinum Android Talks #20 - DiffUtil
Infinum Android Talks #20 - Benefits of using Kotlin
Infinum iOS Talks #4 - Making our VIPER more reactive
Infinum iOS Talks #4 - Making your Swift networking code more awesome with Re...
Infinum Android Talks #13 - Using ViewDragHelper
Infinum Android Talks #14 - Log4j
Infinum Android Talks #9 - Making your app location-aware
Infinum Android Talks #14 - Gradle plugins
Infinum Android Talks #14 - Facebook for Android API
Infinum Android Talks #19 - Stop wasting time fixing bugs with TDD by Domagoj...
Infinum Android Talks #18 - Create fun lists by Ivan Marić
Infinum Android Talks #18 - In-app billing by Ivan Marić
Infinum Android Talks #18 - How to cache like a boss by Željko Plesac
Infinum iOS Talks #2 - VIPER for everybody by Damjan Vujaklija
Infinum iOS Talks #2 - Xamarin by Ivan Đikić
Infinum iOS Talks #1 - Swift under the hood: Method Dispatching by Vlaho Poluta
Infinum iOS Talks #1 - Swift done right by Ivan Dikic
Infinum iOS Talks #1 - Becoming an iOS developer swiftly by Vedran Burojevic
Infinum Android Talks #17 - A quest for WebSockets by Zeljko Plesac

Recently uploaded (20)

PDF
How to Migrate SBCGlobal Email to Yahoo Easily
PDF
How to Choose the Right IT Partner for Your Business in Malaysia
PPTX
ISO 45001 Occupational Health and Safety Management System
PPTX
Agentic AI Use Case- Contract Lifecycle Management (CLM).pptx
PPT
Introduction Database Management System for Course Database
PPTX
CHAPTER 2 - PM Management and IT Context
PPTX
Operating system designcfffgfgggggggvggggggggg
PDF
Flood Susceptibility Mapping Using Image-Based 2D-CNN Deep Learnin. Overview ...
PPTX
Online Work Permit System for Fast Permit Processing
PDF
PTS Company Brochure 2025 (1).pdf.......
PDF
Nekopoi APK 2025 free lastest update
PDF
Wondershare Filmora 15 Crack With Activation Key [2025
PDF
Internet Downloader Manager (IDM) Crack 6.42 Build 42 Updates Latest 2025
PPTX
history of c programming in notes for students .pptx
PPTX
ManageIQ - Sprint 268 Review - Slide Deck
PDF
Odoo Companies in India – Driving Business Transformation.pdf
PDF
Claude Code: Everyone is a 10x Developer - A Comprehensive AI-Powered CLI Tool
PDF
System and Network Administration Chapter 2
PDF
Adobe Illustrator 28.6 Crack My Vision of Vector Design
PPTX
Oracle E-Business Suite: A Comprehensive Guide for Modern Enterprises
How to Migrate SBCGlobal Email to Yahoo Easily
How to Choose the Right IT Partner for Your Business in Malaysia
ISO 45001 Occupational Health and Safety Management System
Agentic AI Use Case- Contract Lifecycle Management (CLM).pptx
Introduction Database Management System for Course Database
CHAPTER 2 - PM Management and IT Context
Operating system designcfffgfgggggggvggggggggg
Flood Susceptibility Mapping Using Image-Based 2D-CNN Deep Learnin. Overview ...
Online Work Permit System for Fast Permit Processing
PTS Company Brochure 2025 (1).pdf.......
Nekopoi APK 2025 free lastest update
Wondershare Filmora 15 Crack With Activation Key [2025
Internet Downloader Manager (IDM) Crack 6.42 Build 42 Updates Latest 2025
history of c programming in notes for students .pptx
ManageIQ - Sprint 268 Review - Slide Deck
Odoo Companies in India – Driving Business Transformation.pdf
Claude Code: Everyone is a 10x Developer - A Comprehensive AI-Powered CLI Tool
System and Network Administration Chapter 2
Adobe Illustrator 28.6 Crack My Vision of Vector Design
Oracle E-Business Suite: A Comprehensive Guide for Modern Enterprises

Infinum Android Talks #17 - Testing your Android applications by Ivan Kust

  • 1. We're an independent design & development agency.
  • 4. ROBOLECTRIC • http://robolectric.org/ • unit test framework • tests run in JVM on your machine
  • 5. ROBOLECTRIC SETUP • 1. add gradle dependencies • 2. write test application class • 3. write test class • 4. run tests
  • 6. 1. ADD GRADLE DEPENDENCIES • make sure “Unit tests” is selected as Test Artifact under Build Variants • add the robolectric dependency in your app build.gradle file:
 testCompile 'junit:junit:4.12'
 testCompile 'org.hamcrest:hamcrest-library:1.3' 
 testCompile 'org.robolectric:robolectric:3.0'
 testCompile 'org.robolectric:shadows-support-v4:3.0'
  • 7. 2. WRITE TEST APPLICATION CLASS • all unit test code goes into test flavour • Test{applicationName} • must extend application class • runs instead of application class in tests • should inject test dependencies
  • 8. 3. WRITE TEST CLASS • create new class in test flavor • specify runner with @RunWith annotation • add @Config annotation • add test methods and annotate them with @Test
  • 9. TEST CONFIGURATION • constants property of @Config annotation is mandatory • for all other options check:
 http://robolectric.org/configuring/ @RunWith(RobolectricGradleTestRunner.class)
 @Config(constants = BuildConfig.class, sdk = 21)
 public class DeckardActivityTest {
 
 @Test 
 public void testSomething() throws Exception { 
 assertTrue(Robolectric.setupActivity(DeckardActivity.class) != null);
 }
 }
  • 10. 4. RUN TESTS • from Android studio • ./gradlew clean test
  • 12. MOCK WEB SERVER • network responses should be mocked in unit tests • speed • consistency
  • 13. GRADLE DEPENDENCIES • add the MockWebServer dependency in your app build.gradle file: 
 • MockWebServer depends on okhttp library • make sure that mockwebserver version matches okhttp version testCompile 'com.squareup.okhttp:mockwebserver:2.7.4'
  • 14. USAGE • 1. instantiate MockWebServer • 2. call start() method • 3. get local server url by calling url(“/“) • 4. inject server local url into networking module • 5. enqueue responses using enqueue() method
  • 15. USAGE • in both unit and instrumentation tests (steps 1 - 4): • prepare and inject MockWebServer in @Before method (called before every @Test method) • stop MockWebServer in @After method (called after every @Test method)
  • 16. USAGE • or in Robolectric unit tests (steps 1 - 4): • prepare and inject MockWebServer in:
 beforeTest(Method) method in Test application • stop MockWebServer in:
 afterTest(Method method) in Test application
  • 17. ENQUEUEING RESPONSES • enqueue(), MockResponse object • https://github.com/square/okhttp/blob/master/ mockwebserver/src/main/java/com/squareup/okhttp/ mockwebserver/MockResponse.java mockWebServer.enqueue( 
 new MockResponse()
 .setResponseCode(200)
 .setBody("Response body");
 );
  • 18. LARGE RESPONSES? • 1. store response body content to a file • 2. put the file inside /test/resources/ directory • 3. read the contents of the file in test: public static String readFromFile(String filename) {
 InputStream is = ResourceUtils.class.getClassLoader().getResourceAsStream(filename);
 return convertStreamToString(is);
 }
  • 19. CHECKING REQUESTS • mockWebServer.getRequestCount() • mockWebServer.takeRequest() • mockWebServer.takeRequest(long, TimeUnit)
  • 20. @Test 
 public void nameOk() throws Exception {
 
 PokemonTestApp.getMockWebServer().enqueue(
 
 new MockResponse()
 .setResponseCode(200)
 .setBody(ResourceUtils.readFromFile("charizard.json"))
 );
 
 
 String resourceUri = "api/v1/pokemon/6/";
 Pokemon pokemon = new Pokemon();
 pokemon.setResourceUri(resourceUri);
 
 Activity activity = buildActivity(pokemon); 
 RecordedRequest request = takeLastRequest();
 
 //Perform the assertions
 
 }
  • 21. (A)SYNCHRONOUS EXECUTORS • unit tests run in a single thread • waiting for background threads complicates tests • solution: Synchronous executors
  • 22. (A)SYNCHRONOUS EXECUTORS • setting executor on Retrofit: 
 
 • specify executor for networking and for callback • for tests: both synchronous return new RestAdapter.Builder() ...
 .setExecutors(new BackgroundExecutor(), new CallbackExecutor()) ...
 .build();
  • 23. SYNCHRONOUS EXECUTOR? • runs the queued runnable in the same thread • simple as that: public class SynchronousExecutor implements Executor {
 
 @Override
 public void execute(Runnable command) {
 command.run();
 }
 }
  • 25. SHADOWING A CLASS • 1. create a custom Robolectric runner • 2. declare shadowed classes in createClassLoaderConfig() method • 3. implement shadow class • 4. run tests with custom runner
  • 26. public class CustomRobolectricGradleTestRunner extends RobolectricGradleTestRunner {
 
 public CustomRobolectricGradleTestRunner(Class<?> klass) throws InitializationError {
 super(klass);
 }
 
 @Override
 protected AndroidManifest getAppManifest(Config config) {
 AndroidManifest appManifest = super.getAppManifest(config); // needs to be the java package, not applicationId
 appManifest.setPackageName("co.infinum.app");
 
 return appManifest;
 }
 
 @Override
 public InstrumentationConfiguration createClassLoaderConfig() {
 InstrumentationConfiguration.Builder builder = InstrumentationConfiguration.newBuilder();
 
 builder.addInstrumentedClass(ShadowOutline.class.getName());
 builder.addInstrumentedClass(ShadowAlertDialogSupportV7.class.getName());
 builder.addInstrumentedClass(ShadowSpinnerView.class.getName());
 return builder.build();
 }
 
 }
  • 27. 3. IMPLEMENT SHADOW CLASS • create a new class with @Implements(OriginalClass.class) annotation • add @Implementation annotation to methods that “override” behaviour from original class • you can leave some methods unchanged • if you wish to use an instance of OriginalClass in your shadow class it must be annotated with @RealObject
  • 28. ADD SHADOWS TO TEST • in order to make your shadows available in test add them to @Config in your test:
 
 @Config(shadows = {ShadowClass.class})
  • 29. @Implements(Outline.class)
 public class ShadowOutline {
 
 @RealObject
 private Outline outline;
 
 public Path path;
 
 public Rect rect;
 
 public float radius;
 
 public float alpha;
 
 @Implementation
 public void setConvexPath(Path convexPath) {
 if (path == null) {
 path = new Path();
 }
 
 path.set(convexPath);
 }
 }
  • 31. SETUP • 1. add gradle dependencies • 2. specify runner • 3. write test class • 4. run
  • 32. 1. ADD DEPENDENCIES • make sure “Android Instrumentation tests” is selected as Test Artifact under Build Variants • add the robolectric dependency in your app build.gradle file: // Espresso
 
 androidTestCompile 'com.android.support.test.espresso:espresso-core:2.2.1'
 androidTestCompile 'com.android.support.test.espresso:espresso-intents:2.2.1'
 androidTestCompile 'com.android.support.test:runner:0.4.1'
 androidTestCompile 'com.android.support.test:rules:0.4.1'
  • 33. 2. SPECIFY RUNNER • specify default instrumentation test runner in application build.gradle: android { defaultConfig { testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" } }
  • 34. 3. WRITE TEST CLASS • create new class in test flavor • annotate with @LargeTest • add field of type ActivityTestRule and annotate with @Rule - defines the activity that will run • add test methods and annotate them with @Test
  • 35. 4. RUN • from Android studio
 • ./gradlew clean 
 connectedAndroidTest
  • 37. ASSERTJ ANDROID • https://github.com/square/assertj-android • extension of AssertJ • you can extend and set up your own assertions
  • 38. //Check that name in details is displayed properly. assertThat(activity.findViewById(R.id.name).getVisibility()) .isEqualTo(View.VISIBLE);
 
 assertThat(((TextView) activity.findViewById(R.id.name))
 .getText()).isEqualTo("Charizard");
  • 39. TEST REPORT • will be generated in:
 /app/build/reports/tests/{flavour}/index.html
 • if tests faill, gradle will print out the location of the report in console as well
  • 40. LOGS • to show Log.d() outputs add folloving in your @Before method:
 
 ShadowLog.stream = System.out;
  • 41. USING MOCK WEB SERVER • like in unit tests (steps 1 - 4): • prepare and inject MockWebServer in @Before method (called before every @Test method) • stop MockWebServer in @After method (called after every @Test method) • note that in instrument tests there is no Test application that you can use
  • 42. RESOURCES • http://robolectric.org/ • https://github.com/square/assertj-android • http://www.vogella.com/tutorials/ AndroidTestingEspresso/article.html • http://developer.android.com/training/testing/ui- testing/espresso-testing.html
  • 43. Thank you! Visit www.infinum.co or find us on social networks: infinum.co infinumco infinumco infinum