You all know what tests are. You all know you need to write them. But also you know it’s hard to start writing tests for mobile app thus you usually neglect it. Let’s look into Android automation testing, what technologies and approaches we can use to have a complete Maslow's Pyramid for testing. Unit Testing, Integration Testing, UI Automation, Mocking etc.
The document discusses Google's Architecture Components, which are a collection of libraries that help handle common tasks in Android development. It covers the main components like Lifecycle, LiveData, ViewModel, and Room. Lifecycle allows activities and fragments to observe lifecycle changes of other objects like LiveData. LiveData is an observable data holder that is lifecycle-aware. ViewModel stores UI-related data to survive configuration changes like screen rotations. Room provides an abstraction layer over SQLite to allow for more robust database access.
The document discusses automated testing of Android applications using Espresso. It covers why automated testing is important, where to use Espresso vs other frameworks like Robolectric depending on the app layer being tested, basic Espresso testing code examples, and 5 tips for writing effective Espresso tests including using page objects, minimizing dependencies, making instances configurable, wrapping Espresso APIs, and avoiding sleeps for asynchronous waits.
Gilt Groupe's Selenium 2 Conversion ChallengesSauce Labs
The document discusses a company's transition from Selenium 1 to Selenium 2 for automated testing. It describes building a custom test framework in Java and migrating over 800 test cases to the new WebDriver API. Challenges included differences in functionality and a lack of documentation. The conversion was done line-by-line over time and resulted in cleaner, more maintainable code and improved test execution speeds on Sauce Labs.
This document provides an overview of key Android development concepts and techniques. It discusses fragments, the support library, dependency injection, image caching, threading and AsyncTask, notifications, supporting multiple screens, and optimizing ListView performance. The document also recommends several popular Android libraries and open source apps that demonstrate best practices.
Efficient and Testable MVVM pattern
김범준
레이니스트 / 안드로이드 개발
레이니스트에서 뱅크샐러드 안드로이드 어플리케이션을 개발하고 있는 5년차 개발자 입니다. Reactive, 함수형 프로그래밍에 관심이 많으며 효율적이고 가독성 있는 코드를 짜는 것을 항상 목표로 부단히 노력중입니다.
This document discusses changes and new features in jQuery versions 1.9, 2.0, and the use of Modernizr for browser feature detection. jQuery 1.9 removed several deprecated functions and made other API changes for consistency. New features included CSS property batching and the .finish() method. jQuery 2.0 reduced file size further and dropped support for older browsers. Modernizr detects CSS and JavaScript features and adds results to the page for conditional styling.
The document discusses Google's Architecture Components, which are a collection of libraries that help handle common tasks in Android development. It covers the main components like Lifecycle, LiveData, ViewModel, and Room. Lifecycle allows activities and fragments to observe lifecycle changes of other objects like LiveData. LiveData is an observable data holder that is lifecycle-aware. ViewModel stores UI-related data to survive configuration changes like screen rotations. Room provides an abstraction layer over SQLite to allow for more robust database access.
The document discusses automated testing of Android applications using Espresso. It covers why automated testing is important, where to use Espresso vs other frameworks like Robolectric depending on the app layer being tested, basic Espresso testing code examples, and 5 tips for writing effective Espresso tests including using page objects, minimizing dependencies, making instances configurable, wrapping Espresso APIs, and avoiding sleeps for asynchronous waits.
Gilt Groupe's Selenium 2 Conversion ChallengesSauce Labs
The document discusses a company's transition from Selenium 1 to Selenium 2 for automated testing. It describes building a custom test framework in Java and migrating over 800 test cases to the new WebDriver API. Challenges included differences in functionality and a lack of documentation. The conversion was done line-by-line over time and resulted in cleaner, more maintainable code and improved test execution speeds on Sauce Labs.
This document provides an overview of key Android development concepts and techniques. It discusses fragments, the support library, dependency injection, image caching, threading and AsyncTask, notifications, supporting multiple screens, and optimizing ListView performance. The document also recommends several popular Android libraries and open source apps that demonstrate best practices.
Efficient and Testable MVVM pattern
김범준
레이니스트 / 안드로이드 개발
레이니스트에서 뱅크샐러드 안드로이드 어플리케이션을 개발하고 있는 5년차 개발자 입니다. Reactive, 함수형 프로그래밍에 관심이 많으며 효율적이고 가독성 있는 코드를 짜는 것을 항상 목표로 부단히 노력중입니다.
This document discusses changes and new features in jQuery versions 1.9, 2.0, and the use of Modernizr for browser feature detection. jQuery 1.9 removed several deprecated functions and made other API changes for consistency. New features included CSS property batching and the .finish() method. jQuery 2.0 reduced file size further and dropped support for older browsers. Modernizr detects CSS and JavaScript features and adds results to the page for conditional styling.
The Ring programming language version 1.8 book - Part 77 of 202Mahmoud Samir Fayed
The Objects Library provides an object-oriented way to manage GUI windows and objects in RingQt applications. It uses classes to represent windows and controllers, and handles connecting events to controller methods. Some key features include opening windows with Open_Window(), creating view and controller classes that inherit from base classes, getting the last opened window with Last_Window(), and setting the parent object with SetParentObject() when opening sub-windows. The library aims to support the MVC pattern and make it easier to work with multiple related windows in RingQt apps.
The Ring programming language version 1.2 book - Part 51 of 84Mahmoud Samir Fayed
This document discusses using the Objects library for building RingQt applications. The library provides an object-oriented approach to managing GUI objects and connecting events. It supports creating multiple windows from the same controller class. Key points:
- The Open_Window() function opens new windows from controller classes derived from WindowsControllerParent.
- Views are defined in classes derived from WindowsViewParent and contain a 'win' attribute for the GUI object.
- Method() determines the controller method executed on events.
- Last_Window() returns the last opened window controller for calling methods like SetParentObject().
- Controller classes contain CloseAction() by default to close windows.
An example creates a main window with
The Ring programming language version 1.7 book - Part 75 of 196Mahmoud Samir Fayed
The Objects Library provides an object-oriented way to manage GUI windows and objects in RingQt applications. It allows creating multiple window controllers and views from the same classes. The library handles connecting events to controller methods and provides easy access to parent/caller windows from child windows. Developers can use the library with the MVC pattern by creating controller and view classes for each window type. Key functions include Open_Window() to create windows, Last_Window() to access the last window, and Method() to link view events to controller methods. The library aims to simplify RingQt application development by handling window and object management.
Visual Component Testing -- w/ Gil Tayar (Applitools) and Gleb Bahmutov (Cyp...Applitools
Full Webinar recording:
Functional and visual testing work very well together for end-to-end frontend tests.
In this hands-on session, Gleb Bahmutov (VP Engineering @ Cypress) and Gil Tayar (Sr. Architect @ Applitools) showed how to apply the same approach to the individual components -- the building blocks of modern web apps.
Component testing ensures a thorough validation of all our components' variants such as different inputs and states, edge-case network responses, and responsive widths.
Gleb and Gil used Cypress to drive the tests and check them functionally, while integrating the Applitools plugin to provide us with the capability to quickly and easily test them visually across all browsers and response widths.
Watch this on-demand webinar to see the full power of the functional and visual component tests ability to speed up the development cycle.
The document discusses Android AOP (Aspect Oriented Programming). It describes key AOP concepts like join points, pointcuts, and advice. It provides examples of how AOP can be used for logging, data validation, and other cross-cutting concerns. It also shows how to set up AOP for Android projects using AspectJ including defining pointcuts and advice.
Struts has outgrown its reputation as a simple web framework and has become more of a brand. Because of this, two next generation frameworks are being developed within the project: Shale and Action 2.0. Action 2.0 is based on WebWork, and though its backing beans are similar to JSF, its architecture is much simpler, and easier to use.
Migrating to Struts Action 2.0 is more about unlearning Struts than it is about learning the "WebWork Way". Once you understand how simple WebWork is, you'll find that Struts Action 2.0 is a powerful framework that supports action-based navigation, page-based navigation, AOP/Interceptors, components and rich Ajax support.
Come to this session to see code comparisons and learn about migration strategies to use the kick-ass web framework of 2006.
The document discusses Android Loaders, which provide a way for Activities and Fragments to asynchronously load data from a data source and deliver it back without having to manage threads or handle configuration changes. Loaders allow data to persist across configuration changes like orientation changes. The document covers the history of loading data in Android including threads and AsyncTask, introduces Loaders and the LoaderManager API, discusses implementing basic Loaders including CursorLoaders, and covers common mistakes to avoid.
This document discusses web components and how to create them. It introduces web components standards like custom elements, templates, HTML imports, and shadow DOM. It describes how to install and use existing web components in HTML. It also explains how to create new web components using the Polymer library and ES6 features like classes, inheritance, static members, arrow functions, and method properties. The document promotes Vaadin Framework for building server-side Java components and integrating them with client-side web components.
Code to DI For - Dependency Injection for Modern ApplicationsCaleb Jenkins
This talk introduces the concepts of factories, strategy pattern, Inversion of Control, dependency injection and several of the available frameworks. We'll also look at common dependency injection patterns and various IoC/DI frameworks, the pros & cons, practical steps and guidance as well some of the real world scenarios with impact to unit testing and application architecture.
First presented at the Ft. Worth .NET Users Group on March 15th, 2016 - http://developingux.com/2016/03/14/code-to-di-for-in-ft-worth/ - Code will be posted to my GitHub soon! https://github.com/calebjenkins/ (Talks.Code-to-DI-For)
The Ring programming language version 1.5.2 book - Part 68 of 181Mahmoud Samir Fayed
This document discusses building RingQt applications for mobile and using the objects library and form designer in Ring.
It provides instructions on downloading requirements like the Android SDK and NDK. It also describes updating the Android SDK and installing Qt for Android. An example is given of creating a simple RingQt application with two window types - a main window and sub windows.
The document explains the objects library, which provides a class-based approach and methods for managing GUI objects and events. An example demonstrates creating multiple sub-windows from a main window. It also covers functions like Open_WindowAndLink() for connecting windows.
Finally, it briefly discusses the form designer in Ring, which allows visually designing GUI forms and can
The document summarizes the New York Times' open source Store library for Android, which provides a unified way to fetch, parse, cache, and retrieve data in Android applications. The Store abstracts these processes and enforces unidirectional data flow while exposing data as RxJava Observables. Key aspects include using StoreBuilders to configure Stores, adding fetchers and parsers, using middleware like GsonSourceParser, and enabling disk caching. The document also provides guidance on open sourcing a new library, including using Android Studio and GitHub to set up the project, adding documentation like README and license, and publishing to Maven Central.
Droidcon2013 pro guard, optimizer and obfuscator in the android sdk_eric lafo...Droidcon Berlin
ProGuard is an open source tool that optimizes and obfuscates Java bytecode. It can shrink code size by removing unused classes, fields, and methods. It optimizes code through optimizations like constant propagation and method inlining. It obfuscates code by renaming classes, fields, and methods to obscure their purpose. ProGuard is included in the Android SDK and can help protect Android apps from reverse engineering.
Learning Java 4 – Swing, SQL, and Security APIcaswenson
This document provides an overview of Java concepts including SQL, security APIs, and Swing. It discusses how to connect to databases and execute queries using JDBC, implement cryptography using the security API, and build graphical user interfaces with Swing components like JFrames, JLabels, and JButtons. The document also provides code examples for working with databases, cryptography, and creating basic Swing interfaces.
SolrJ: Power and Pitfalls - Jason Gerlowski, LucidworksLucidworks
This document summarizes SolrJ, a Java client library for interacting with Apache Solr. It provides an overview of SolrJ's history and common usage patterns. It also discusses some common mistakes in SolrJ usage and potential areas for improvement, such as supporting HTTP/2 and allowing customization of load balancing. The document concludes with a list of important SolrJ classes.
Struts 2 uses interceptors based on the intercepting filter design pattern. It follows a pull-MVC architecture where the view layer retrieves data stored in the value stack by the controller. Interceptors are not thread-safe. Interceptors and filters both intercept requests, but interceptors are specific to Struts 2, can be configured to call methods conditionally, and replace the need for some filters. The front controller in Struts 2 is a filter rather than a servlet to avoid loading issues and allow interceptors to replace some filters. Actions serve as both models and controllers by containing business logic and data for the view. Interceptors make Struts 2 more configurable, reusable, and integrated with other frameworks compared
The best practices approach for organizing Android applications into logical components has been widely debated by the developer community over the last several years. If you’ve had trouble choosing between MVC, MVP, MVVM and Reactive Architectures, or even understanding how they differ exactly, you’re not alone! Up until now, there has been no official guidance from Google, however at IO’17, Google announced Android Architecture Components as a recommended pattern moving forward. In this session you’ll learn how these architectural patterns relate to each other and the motivations behind each. You’ll also learn how to apply Android Architecture Components effectively through from live code and interactive demonstrations.
The Mobile Vision API provides a framework for recognizing objects in photos and videos. The framework includes detectors, which locate and describe visual objects in images or video frames, and an event-driven API that tracks the position of those objects in video.
This document discusses unit testing Android applications using Robolectric. It introduces Robolectric as a tool that allows loading and testing Android classes in pure Java projects. It then discusses various testing techniques using Robolectric including mocking Android classes and context, using spies, and reducing the use of shadows by leveraging value qualifiers. The document emphasizes removing shadows as much as possible to get closer to real code.
The document discusses using annotations in Java, providing examples of annotations for servlets, EJBs, web services, CDI, and using frameworks like JUnit, Spring, Javassist, and ASM. It presents code samples to define servlets, session beans, RESTful and SOAP web services, and component injection using annotations instead of XML configurations. The document also demonstrates how to programmatically read annotation values and metadata using reflection, Javassist, and ASM.
This document provides an overview of various testing frameworks and concepts used for Android testing. It discusses JUnit, Mockito, PowerMock, Robolectric, and Espresso - the most popular tools for unit, integration, and UI testing of Android apps. For each tool, it provides brief descriptions of their purpose and capabilities. It also includes examples demonstrating how to write tests using JUnit, Mockito, and PowerMock. The document aims to explain what these testing tools are and how they can be used for testing Android applications.
A simple presentation that I did at work that goes over Unit Test, Mocking and TDD to improve development, it is explained from a Java perspective but can be helpful to apply TDD to other languages as well.
The Ring programming language version 1.8 book - Part 77 of 202Mahmoud Samir Fayed
The Objects Library provides an object-oriented way to manage GUI windows and objects in RingQt applications. It uses classes to represent windows and controllers, and handles connecting events to controller methods. Some key features include opening windows with Open_Window(), creating view and controller classes that inherit from base classes, getting the last opened window with Last_Window(), and setting the parent object with SetParentObject() when opening sub-windows. The library aims to support the MVC pattern and make it easier to work with multiple related windows in RingQt apps.
The Ring programming language version 1.2 book - Part 51 of 84Mahmoud Samir Fayed
This document discusses using the Objects library for building RingQt applications. The library provides an object-oriented approach to managing GUI objects and connecting events. It supports creating multiple windows from the same controller class. Key points:
- The Open_Window() function opens new windows from controller classes derived from WindowsControllerParent.
- Views are defined in classes derived from WindowsViewParent and contain a 'win' attribute for the GUI object.
- Method() determines the controller method executed on events.
- Last_Window() returns the last opened window controller for calling methods like SetParentObject().
- Controller classes contain CloseAction() by default to close windows.
An example creates a main window with
The Ring programming language version 1.7 book - Part 75 of 196Mahmoud Samir Fayed
The Objects Library provides an object-oriented way to manage GUI windows and objects in RingQt applications. It allows creating multiple window controllers and views from the same classes. The library handles connecting events to controller methods and provides easy access to parent/caller windows from child windows. Developers can use the library with the MVC pattern by creating controller and view classes for each window type. Key functions include Open_Window() to create windows, Last_Window() to access the last window, and Method() to link view events to controller methods. The library aims to simplify RingQt application development by handling window and object management.
Visual Component Testing -- w/ Gil Tayar (Applitools) and Gleb Bahmutov (Cyp...Applitools
Full Webinar recording:
Functional and visual testing work very well together for end-to-end frontend tests.
In this hands-on session, Gleb Bahmutov (VP Engineering @ Cypress) and Gil Tayar (Sr. Architect @ Applitools) showed how to apply the same approach to the individual components -- the building blocks of modern web apps.
Component testing ensures a thorough validation of all our components' variants such as different inputs and states, edge-case network responses, and responsive widths.
Gleb and Gil used Cypress to drive the tests and check them functionally, while integrating the Applitools plugin to provide us with the capability to quickly and easily test them visually across all browsers and response widths.
Watch this on-demand webinar to see the full power of the functional and visual component tests ability to speed up the development cycle.
The document discusses Android AOP (Aspect Oriented Programming). It describes key AOP concepts like join points, pointcuts, and advice. It provides examples of how AOP can be used for logging, data validation, and other cross-cutting concerns. It also shows how to set up AOP for Android projects using AspectJ including defining pointcuts and advice.
Struts has outgrown its reputation as a simple web framework and has become more of a brand. Because of this, two next generation frameworks are being developed within the project: Shale and Action 2.0. Action 2.0 is based on WebWork, and though its backing beans are similar to JSF, its architecture is much simpler, and easier to use.
Migrating to Struts Action 2.0 is more about unlearning Struts than it is about learning the "WebWork Way". Once you understand how simple WebWork is, you'll find that Struts Action 2.0 is a powerful framework that supports action-based navigation, page-based navigation, AOP/Interceptors, components and rich Ajax support.
Come to this session to see code comparisons and learn about migration strategies to use the kick-ass web framework of 2006.
The document discusses Android Loaders, which provide a way for Activities and Fragments to asynchronously load data from a data source and deliver it back without having to manage threads or handle configuration changes. Loaders allow data to persist across configuration changes like orientation changes. The document covers the history of loading data in Android including threads and AsyncTask, introduces Loaders and the LoaderManager API, discusses implementing basic Loaders including CursorLoaders, and covers common mistakes to avoid.
This document discusses web components and how to create them. It introduces web components standards like custom elements, templates, HTML imports, and shadow DOM. It describes how to install and use existing web components in HTML. It also explains how to create new web components using the Polymer library and ES6 features like classes, inheritance, static members, arrow functions, and method properties. The document promotes Vaadin Framework for building server-side Java components and integrating them with client-side web components.
Code to DI For - Dependency Injection for Modern ApplicationsCaleb Jenkins
This talk introduces the concepts of factories, strategy pattern, Inversion of Control, dependency injection and several of the available frameworks. We'll also look at common dependency injection patterns and various IoC/DI frameworks, the pros & cons, practical steps and guidance as well some of the real world scenarios with impact to unit testing and application architecture.
First presented at the Ft. Worth .NET Users Group on March 15th, 2016 - http://developingux.com/2016/03/14/code-to-di-for-in-ft-worth/ - Code will be posted to my GitHub soon! https://github.com/calebjenkins/ (Talks.Code-to-DI-For)
The Ring programming language version 1.5.2 book - Part 68 of 181Mahmoud Samir Fayed
This document discusses building RingQt applications for mobile and using the objects library and form designer in Ring.
It provides instructions on downloading requirements like the Android SDK and NDK. It also describes updating the Android SDK and installing Qt for Android. An example is given of creating a simple RingQt application with two window types - a main window and sub windows.
The document explains the objects library, which provides a class-based approach and methods for managing GUI objects and events. An example demonstrates creating multiple sub-windows from a main window. It also covers functions like Open_WindowAndLink() for connecting windows.
Finally, it briefly discusses the form designer in Ring, which allows visually designing GUI forms and can
The document summarizes the New York Times' open source Store library for Android, which provides a unified way to fetch, parse, cache, and retrieve data in Android applications. The Store abstracts these processes and enforces unidirectional data flow while exposing data as RxJava Observables. Key aspects include using StoreBuilders to configure Stores, adding fetchers and parsers, using middleware like GsonSourceParser, and enabling disk caching. The document also provides guidance on open sourcing a new library, including using Android Studio and GitHub to set up the project, adding documentation like README and license, and publishing to Maven Central.
Droidcon2013 pro guard, optimizer and obfuscator in the android sdk_eric lafo...Droidcon Berlin
ProGuard is an open source tool that optimizes and obfuscates Java bytecode. It can shrink code size by removing unused classes, fields, and methods. It optimizes code through optimizations like constant propagation and method inlining. It obfuscates code by renaming classes, fields, and methods to obscure their purpose. ProGuard is included in the Android SDK and can help protect Android apps from reverse engineering.
Learning Java 4 – Swing, SQL, and Security APIcaswenson
This document provides an overview of Java concepts including SQL, security APIs, and Swing. It discusses how to connect to databases and execute queries using JDBC, implement cryptography using the security API, and build graphical user interfaces with Swing components like JFrames, JLabels, and JButtons. The document also provides code examples for working with databases, cryptography, and creating basic Swing interfaces.
SolrJ: Power and Pitfalls - Jason Gerlowski, LucidworksLucidworks
This document summarizes SolrJ, a Java client library for interacting with Apache Solr. It provides an overview of SolrJ's history and common usage patterns. It also discusses some common mistakes in SolrJ usage and potential areas for improvement, such as supporting HTTP/2 and allowing customization of load balancing. The document concludes with a list of important SolrJ classes.
Struts 2 uses interceptors based on the intercepting filter design pattern. It follows a pull-MVC architecture where the view layer retrieves data stored in the value stack by the controller. Interceptors are not thread-safe. Interceptors and filters both intercept requests, but interceptors are specific to Struts 2, can be configured to call methods conditionally, and replace the need for some filters. The front controller in Struts 2 is a filter rather than a servlet to avoid loading issues and allow interceptors to replace some filters. Actions serve as both models and controllers by containing business logic and data for the view. Interceptors make Struts 2 more configurable, reusable, and integrated with other frameworks compared
The best practices approach for organizing Android applications into logical components has been widely debated by the developer community over the last several years. If you’ve had trouble choosing between MVC, MVP, MVVM and Reactive Architectures, or even understanding how they differ exactly, you’re not alone! Up until now, there has been no official guidance from Google, however at IO’17, Google announced Android Architecture Components as a recommended pattern moving forward. In this session you’ll learn how these architectural patterns relate to each other and the motivations behind each. You’ll also learn how to apply Android Architecture Components effectively through from live code and interactive demonstrations.
The Mobile Vision API provides a framework for recognizing objects in photos and videos. The framework includes detectors, which locate and describe visual objects in images or video frames, and an event-driven API that tracks the position of those objects in video.
This document discusses unit testing Android applications using Robolectric. It introduces Robolectric as a tool that allows loading and testing Android classes in pure Java projects. It then discusses various testing techniques using Robolectric including mocking Android classes and context, using spies, and reducing the use of shadows by leveraging value qualifiers. The document emphasizes removing shadows as much as possible to get closer to real code.
The document discusses using annotations in Java, providing examples of annotations for servlets, EJBs, web services, CDI, and using frameworks like JUnit, Spring, Javassist, and ASM. It presents code samples to define servlets, session beans, RESTful and SOAP web services, and component injection using annotations instead of XML configurations. The document also demonstrates how to programmatically read annotation values and metadata using reflection, Javassist, and ASM.
This document provides an overview of various testing frameworks and concepts used for Android testing. It discusses JUnit, Mockito, PowerMock, Robolectric, and Espresso - the most popular tools for unit, integration, and UI testing of Android apps. For each tool, it provides brief descriptions of their purpose and capabilities. It also includes examples demonstrating how to write tests using JUnit, Mockito, and PowerMock. The document aims to explain what these testing tools are and how they can be used for testing Android applications.
A simple presentation that I did at work that goes over Unit Test, Mocking and TDD to improve development, it is explained from a Java perspective but can be helpful to apply TDD to other languages as well.
Thomas braun dependency-injection_with_robo_guice-presentation-finalDroidcon Berlin
The document discusses dependency injection (DI) using RoboGuice in Android applications. DI makes code more concise, modular, and easier to test by allowing classes to declare dependencies without knowing how they are satisfied. RoboGuice uses annotations to inject dependencies into activities and services. It allows for loose coupling, high cohesion, and centralized configuration through bindings. DI improves testability by increasing controllability, observability, and isolation of units under test.
Quality assurance and testing are very important in a life cycle of any application. Although, by far not all developers understand the significance of tests.
In this presentation, we cover the basic testing practices for developers. The following tools are discussed: JUnit, Mockito, Hamcrest, JsTestDriver, DBUnit, Arquillian, SoapUI, Selenium.
Guide to the jungle of testing frameworksTomáš Kypta
There are many tools, libraries and frameworks available for Android developers to test their applications. The jungle is huge and it's not easy to find the right ones. Some frameworks are good for unit testing, some are good for instrumentation testing, and some can be used for both. Some have great capabilities but annoying weaknesses. Some are good for testing UI, other allow you to make good mocks. We will look at many frameworks, the popular ones like Mockito, Robolectric, Espresso, and some other.
Presented at GDG DevFest Minsk 2016.
Unit Testing on Android involves testing individual units or components of code to find and fix bugs early. There are several test frameworks for Android like JUnit and Mockito that make unit testing easier. JUnit provides annotations to mark test methods and assertions to validate results. Mockito allows mocking dependencies to isolate and focus on the code being tested. Robolectric runs tests directly on a JVM without needing an emulator for faster testing. Code coverage tools like JaCoCo measure how much code is executed during tests.
A collection of libraries that help you design robust, testable, and maintainable apps. Start with classes for managing your UI component lifecycle and handling data persistence.
Unit & Automation Testing in Android - Stanislav Gatsev, MelonbeITconference
Stanislav Gatsev presents on unit and automation testing on Android. He discusses why automation testing is important for saving time, improving code quality, and supporting live documentation. He covers using JUnit and Mockito for testing, as well as activity testing with ActivityInstrumentationTestCase2 and user interface testing with Robotium. Mock objects are used to replace dependencies and allow testing in isolation. Examples are provided of writing unit tests, activity tests, and tests using Robotium to simulate user interactions.
SWTBot is a tool for automating UI tests of Eclipse plug-ins. The document covers setting up SWTBot, challenges of UI testing, exercises in using the SWTBot API to find widgets and perform actions, best practices like using abstractions and page objects, and tips for logging and timeouts. Key points include using matchers to find widgets robustly, ensuring thread safety, and modeling capabilities rather than UI elements.
Google Guice is a dependency injection framework for Java that allows configuration through modules defined as Java classes rather than external files. It uses annotations and generics for type-safe bindings and easy refactoring. A simple example demonstrates how Guice can inject a mock DAO for tests versus a real JDBC DAO for the application by configuring different modules for the test injector and application injector. This avoids the need to directly instantiate dependencies in classes like UserController.
This document provides an overview of CDI (Contexts and Dependency Injection) and some portable CDI extensions, including Apache DeltaSpike. It discusses key CDI concepts like dependency injection, interceptors, events, and scopes. It introduces Apache OpenWebBeans as a fast and stable CDI container implementation. It then demonstrates how DeltaSpike extends CDI with additional features like transaction management, qualifiers, specialized configuration, and alternatives. The document encourages involvement to help shape the future of Apache DeltaSpike.
Developing a Sling application is only half the story - or perhaps even less. Automated testing is of great importance for insuring code quality and reducing regression risk. Sling presents an interesting challenge, as its technology stack does not get as much attention as more mainstream ones. As such, we had the pleasure of developing our own patterns and testing tools, while integrating the foundations that already existed. This presentation will walk through the various available tools and show how they can be used to cover a Sling-based application.
This document provides an overview of JUnit 5 and TestContainers. It discusses how JUnit 5 is composed of the JUnit Platform, JUnit Jupiter, and JUnit Vintage modules. It covers JUnit 5 annotations, assertions, assumptions, parameterized and conditional tests. It also discusses how TestContainers allows tests to use live Docker containers as their test environment by launching containers during tests. This includes using generic containers, specialized database containers, and configuring container properties. Resources for further learning about both tools are also provided.
The document discusses programming paradigms and introduces aspect-oriented programming (AOP). It provides an example of implementing logging functionality as an aspect to separate cross-cutting concerns from the core program logic. The example of a health monitoring system using remote method invocation (RMI) demonstrates how AOP can help modularize distributed functionality and address issues like tangled and spread code.
Paradigmas de linguagens de programacao - aula#9Ismar Silveira
The document discusses programming paradigms and presents an example of implementing a health complaint tracking system using aspects of programming (AOP) to modularize distributed functionality. It describes how AOP can be used to separate the core object-oriented code from cross-cutting distribution concerns implemented through remote method invocation (RMI). The example shows how an aspect module centralizes the RMI-related code and avoids tangling it within core classes.
- The document discusses various topics around testing Android applications such as creating test projects, different types of tests (unit, integration, UI, etc.), testing frameworks like JUnit, using annotations, running and debugging tests.
- It provides an overview of key concepts and tools required for testing including testing on emulators and real devices, using mocks, assertions and view assertions in tests.
- The document demonstrates how to structure tests, write test cases with different assertions and annotations, and debug issues by running tests in Eclipse and from the command line.
Unit testing and integration testing are software testing techniques. Unit testing involves validating individual units or components of code work properly. Integration testing involves combining units and testing them together to find interface defects. An example integration test scenario described combining database scripts, application code, and GUI components developed separately into one system and verifying the interfaces. TestNG is a testing framework that supports features like dependency testing, grouping tests, and parameterization to make testing more powerful than JUnit.
This document provides an overview of Robotium, an open source test framework for Android. The presentation covers what Robotium is, how to set it up, why it's needed compared to standard Android testing, how to write tests using the Robotium Solo API, tips and tricks, and additional resources. The purpose of Robotium is to simplify Android testing by providing instrumentation of UI components without needing deep knowledge of Android internals or how the app works.
This document provides an overview of Spring Boot and some of its key features. It discusses the origins and modules of Spring, how Spring Boot simplifies configuration and dependency management. It then covers examples of building Spring Boot applications that connect to a SQL database, use RabbitMQ for messaging, and schedule and run asynchronous tasks.
Similar to Alexey Buzdin "Maslow's Pyramid of Android Testing" (20)
Denis Radin - "Applying NASA coding guidelines to JavaScript or airspace is c...IT Event
The document discusses NASA code guidelines that can be applied to JavaScript development. It outlines 10 rules for writing reliable JavaScript code, including doing one thing per function, limiting control flow constructs, avoiding dynamic memory allocation, adding assertions, limiting scope, and compiling with all warnings enabled. The guidelines are presented alongside images related to space exploration and aviation to illustrate the importance of writing stable code for critical systems.
Sara Harkousse - "Web Components: It's all rainbows and unicorns! Is it?"IT Event
Web components are a tale of four w3c specifications. They are a hot topic now. We’ve all seen big headlines, for instance, “The Web Components revolution”, “Web Components are a game changer”, “A Tectonic Shift for Web Development”, … and so many others. They are certainly exciting and promising, nevertheless, there are some factors holding them back such as performance issues and lack of browser support. Some features seems to be more hassle than they’re worth. In this talk you’ll examine web components from a pragmatic stand point. So if you want to start using web components in production, come to learn what features can you use today. Actually, despite the still short browser support, some of web components features seems to be the best choice to start with . The assessment you’ll learn is the reflection of my personal research and work on my spare time and also feedbacks from my co-workers.
Max Voloshin - "Organization of frontend development for products with micros...IT Event
While our product was growing our team came to need to implement microservices. Later it became obvious that our approaches on organization of frontend development should be rethought and significantly improved.
The report contains our team's solutions for simple and comfortable frontend product development with microservices. Also, this talk is about how we along with the way updated frontend framework, separated frontend and backend, solved internalization problem and started using Docker for front end tasks.
Roman Romanovsky, Sergey Rak - "JavaScript в IoT "IT Event
I've been surprised how easy it is today to program hardware containing Wi-Fi module and start receiving data from a chosen sensor (those perceiving motion, light or sound, etc.). Without a line in C++, all in JavaScript solely.
Together with Sergey, we'll elaborate more on how any frontend engineer can easily jumpstart his journey within the Internet of Things.
Konstantin Krivlenia - "Continuous integration for frontend"IT Event
Do you want to know what is the continuous integration? how does make a controlled code when team is growing, maintain quality of code and be calm after the release. Don't be afraid to use ruthless refactoring and don't break the product features. I am glad to share with you how it make.
Illya Klymov - "Vue.JS: What did I swap React for in 2017 and why?"IT Event
The world of frontend development is changing rapidly. No one stays at the top for a long time. Just yesterday we saw the triumph of React, but today Angular2 treads on its heels. Why have I chosen Vue in 2017? Why not to use a usual React? Have the Chinese managed to create a "silver bullet"? In this report we'll consider these questions and we'll find out why Vue is at the top among JS-frameworks on GitHub and whether it's worth chosing it.
Evgeny Gusev - "A circular firing squad: How technologies drag frontend down"IT Event
Twitterati rules today's world of frontend: popularity equals life. On the one hand, this is good: you can write your own application without spending money and ""rock the world."" And on the other hand — now the frontend world is like a line of the famous song: ""There are nine million bicycles ..."" Is it good or bad? That's what is going to be figured out.
What is a life cycle of technology and is the world really ruled by secret backstage; do React developers really have the highest salaries? In what direction the frontend world goes? In this session, listeners of the talk will see the most interesting examples of frameworks and hear the answers to these and other questions.
Vladimir Grinenko - "Dependencies in component web done right"IT Event
We live in a component-based world. Complex components are based on simple ones. This implies the need to express dependencies between them. Most existing methods have notable disadvantages: hardcode, refactoring complexity, large amount of manual work and so on. Let’s fix it!
Dmitry Bartalevich - "How to train your WebVR"IT Event
Nowadays frontend developer is quite bored - news about new JS-based language aren't exciting, just like about new frameworks. And one day, while writing another logic of the another component or, Jesus Christ, bug fixing IE9, you can find absolutely charming create - WebVR.
In my lecture I'm going to share some secred knowledge about its behaviour, training tools, as well as gained experience.
Nowadays, there are many tips how start your project following the "Offline First" principle. But how add a support offline mode for applications that have already been released? What tactics and architectural approaches are used? What technologies and libraries are looking for? What storages are needed for implementation of pull/push strategies?
James Allardice - "Building a better login with the credential management API"IT Event
Login pages are probably the single type of page that users on the web interact with more than any other. In recent years the sign in experience has changed with the advent of federation via social networks, but whether a user has to type an email address and password or click a link and be redirected via Facebook, the process still interrupts the journey. The Credential Management API, designed by Mike West at Google, is an attempt to help streamline this process at the user agent level. This talk will investigate the new API and explore how we can use it to progressively enhance customer journeys in the apps we build.
Fedor Skuratov "Dark Social: as messengers change the market of social media ...IT Event
– Dark Social. Email, messengers, dark Internet.
– 3 billion in messengers from where all these people undertook and that they do there.
– The whole world – Wechat, and people in it Chinese. As the Asian model wins the West.
– Telegram-channels. As ordinary function not of the most popular messenger caused the real alarm in Russia.
– What’s next? Where the market in a year will come.
Андрей Зайчиков "Архитектура распределенных кластеров NoSQL на AWS"IT Event
Мы рассмотрим важные особенности построения архитектуры распреденных кластеров NoSQL с использованием ресурсов Amazon Web Services, мы затронем такие аспекты как: архитектура гео распределенных кластеров, оптимизация производительности, выбор основных опций для деплоймента и ряд других аспектов. В докладе мы сконцентрируемся на таких популярных базах данных, как Cassandra, MongoDB и некоторых других.
Алексей Рагозин "Java и linux борьба за микросекунды"IT Event
Java используется для широкого спектра приложений, некоторые из них могут иметь жёсткие требования по времени отклика.
Но если речь идёт про сотни микросекунд, годится ли Java, в принципе, для таких задач?
Доклад осветит практические аспекты разработки решений с малым временем отклика на платформе Java + Linux
Volodymyr Lyubinets "Introduction to big data processing with Apache Spark"IT Event
In this talk we’ll explore Apache Spark — the most popular cluster computing framework right now. We’ll look at the improvements that Spark brought over Hadoop MapReduce and what makes Spark so fast; explore Spark programming model and RDDs; and look at some sample use cases for Spark and big data in general.
This talk will be interesting for people who have little or no experience with Spark and would like to learn more about it. It will also be interesting to a general engineering audience as we’ll go over the Spark programming model and some engineering tricks that make Spark fast.
Опубликовав в своём блоге знаменитую заметку о переезде с PostgreSQL на MySQL, Uber наделал много шума в постгресовом сообществе. Для многих из разработчиков PostgreSQL это стало толчком к осознанию несовершенства постгресового табличного движка (который пока всё ещё один). В данном докладе будет разобран пост Uber’а глазами разработчика PostgreSQL. Я расскажу с какими пунктами «обвинения» я согласен, с какими не согласен, а с какими – согласен частично. Также я разберу разработки сообщества в данном направлении и то, насколько они, на мой взгляд, позволяют преодолеть указанные недостатки.
Александр Крашенинников "Hadoop High Availability: опыт Badoo"IT Event
Инфраструктура Hadoop – популярное решение для таких задач, как распределённое хранение данных и вычисления Map/Reduce на кластере. Хорошая масштабируемость и развитая экосистема подкупают и обеспечивают Hadoop’у прочное место в инфраструктуре различных информационных систем. Но чем больше ответственности возлагается на этот компонент, тем важнее обеспечивать его отказоустойчивость и high availability.
Leonid Vasilyev "Building, deploying and running production code at Dropbox"IT Event
Reproducible builds, fast and safe deployment process together with self-healing services form the basis of stable and maintainable infrastructure. In this talk I’d like to cover, from the Site Reliability Engineering (SRE) perspective, how Dropbox addresses above challenges, what technologies are used and what lessons were learnt during implementation process.
Анатолий Пласковский "Миллионы карточных платежей за месяц, или как потерять ...IT Event
Этот доклад – история организации и проведения «боевой стрельбы». Я расскажу о том, как реализовать нагрузочное тестирование реальными платежами без перерывов в работе системы. А также о том, как такой эксперимент может внезапно подорожать на 10 тысяч евро.
Mete Atamel "Resilient microservices with kubernetes"IT Event
Talk description: Creating a single microservice is a well understood problem. Creating a cluster of load-balanced microservices that are resilient and self-healing is not so easy. Managing that cluster with rollouts and rollbacks, scaling individual services on demand, securely sharing secrets and configuration among services is even harder.
Assessment and Planning in Educational technology.pptxKavitha Krishnan
In an education system, it is understood that assessment is only for the students, but on the other hand, the Assessment of teachers is also an important aspect of the education system that ensures teachers are providing high-quality instruction to students. The assessment process can be used to provide feedback and support for professional development, to inform decisions about teacher retention or promotion, or to evaluate teacher effectiveness for accountability purposes.
Main Java[All of the Base Concepts}.docxadhitya5119
This is part 1 of my Java Learning Journey. This Contains Custom methods, classes, constructors, packages, multithreading , try- catch block, finally block and more.
How to Build a Module in Odoo 17 Using the Scaffold MethodCeline George
Odoo provides an option for creating a module by using a single line command. By using this command the user can make a whole structure of a module. It is very easy for a beginner to make a module. There is no need to make each file manually. This slide will show how to create a module using the scaffold method.
A workshop hosted by the South African Journal of Science aimed at postgraduate students and early career researchers with little or no experience in writing and publishing journal articles.
How to Manage Your Lost Opportunities in Odoo 17 CRMCeline George
Odoo 17 CRM allows us to track why we lose sales opportunities with "Lost Reasons." This helps analyze our sales process and identify areas for improvement. Here's how to configure lost reasons in Odoo 17 CRM
This presentation includes basic of PCOS their pathology and treatment and also Ayurveda correlation of PCOS and Ayurvedic line of treatment mentioned in classics.
it describes the bony anatomy including the femoral head , acetabulum, labrum . also discusses the capsule , ligaments . muscle that act on the hip joint and the range of motion are outlined. factors affecting hip joint stability and weight transmission through the joint are summarized.
বাংলাদেশের অর্থনৈতিক সমীক্ষা ২০২৪ [Bangladesh Economic Review 2024 Bangla.pdf] কম্পিউটার , ট্যাব ও স্মার্ট ফোন ভার্সন সহ সম্পূর্ণ বাংলা ই-বুক বা pdf বই " সুচিপত্র ...বুকমার্ক মেনু 🔖 ও হাইপার লিংক মেনু 📝👆 যুক্ত ..
আমাদের সবার জন্য খুব খুব গুরুত্বপূর্ণ একটি বই ..বিসিএস, ব্যাংক, ইউনিভার্সিটি ভর্তি ও যে কোন প্রতিযোগিতা মূলক পরীক্ষার জন্য এর খুব ইম্পরট্যান্ট একটি বিষয় ...তাছাড়া বাংলাদেশের সাম্প্রতিক যে কোন ডাটা বা তথ্য এই বইতে পাবেন ...
তাই একজন নাগরিক হিসাবে এই তথ্য গুলো আপনার জানা প্রয়োজন ...।
বিসিএস ও ব্যাংক এর লিখিত পরীক্ষা ...+এছাড়া মাধ্যমিক ও উচ্চমাধ্যমিকের স্টুডেন্টদের জন্য অনেক কাজে আসবে ...
This presentation was provided by Steph Pollock of The American Psychological Association’s Journals Program, and Damita Snow, of The American Society of Civil Engineers (ASCE), for the initial session of NISO's 2024 Training Series "DEIA in the Scholarly Landscape." Session One: 'Setting Expectations: a DEIA Primer,' was held June 6, 2024.
ISO/IEC 27001, ISO/IEC 42001, and GDPR: Best Practices for Implementation and...PECB
Denis is a dynamic and results-driven Chief Information Officer (CIO) with a distinguished career spanning information systems analysis and technical project management. With a proven track record of spearheading the design and delivery of cutting-edge Information Management solutions, he has consistently elevated business operations, streamlined reporting functions, and maximized process efficiency.
Certified as an ISO/IEC 27001: Information Security Management Systems (ISMS) Lead Implementer, Data Protection Officer, and Cyber Risks Analyst, Denis brings a heightened focus on data security, privacy, and cyber resilience to every endeavor.
His expertise extends across a diverse spectrum of reporting, database, and web development applications, underpinned by an exceptional grasp of data storage and virtualization technologies. His proficiency in application testing, database administration, and data cleansing ensures seamless execution of complex projects.
What sets Denis apart is his comprehensive understanding of Business and Systems Analysis technologies, honed through involvement in all phases of the Software Development Lifecycle (SDLC). From meticulous requirements gathering to precise analysis, innovative design, rigorous development, thorough testing, and successful implementation, he has consistently delivered exceptional results.
Throughout his career, he has taken on multifaceted roles, from leading technical project management teams to owning solutions that drive operational excellence. His conscientious and proactive approach is unwavering, whether he is working independently or collaboratively within a team. His ability to connect with colleagues on a personal level underscores his commitment to fostering a harmonious and productive workplace environment.
Date: May 29, 2024
Tags: Information Security, ISO/IEC 27001, ISO/IEC 42001, Artificial Intelligence, GDPR
-------------------------------------------------------------------------------
Find out more about ISO training and certification services
Training: ISO/IEC 27001 Information Security Management System - EN | PECB
ISO/IEC 42001 Artificial Intelligence Management System - EN | PECB
General Data Protection Regulation (GDPR) - Training Courses - EN | PECB
Webinars: https://pecb.com/webinars
Article: https://pecb.com/article
-------------------------------------------------------------------------------
For more information about PECB:
Website: https://pecb.com/
LinkedIn: https://www.linkedin.com/company/pecb/
Facebook: https://www.facebook.com/PECBInternational/
Slideshare: http://www.slideshare.net/PECBCERTIFICATION
10. Unit Test
๏ Uses simple JUnit
๏ Runs on JVM, not on a device
๏ Lightning fast (5k test in 10
seconds)
๏ Needs Android SDK Stubs
11. static protected void markConflicting(ArrayList<ScheduleItem> items) {
for (int i=0; i<items.size(); i++) {
ScheduleItem item = items.get(i);
// Notice that we only care about sessions when checking conflicts.
if (item.type == ScheduleItem.SESSION) for (int j=i+1; j<items.size(); j++) {
ScheduleItem other = items.get(j);
if (item.type == ScheduleItem.SESSION) {
if (intersect(other, item, true)) {
other.flags |= ScheduleItem.FLAG_CONFLICTS_WITH_PREVIOUS;
item.flags |= ScheduleItem.FLAG_CONFLICTS_WITH_NEXT;
} else {
// we assume the list is ordered by starttime
break;
}
}
}
}
} https://github.com/google/iosched
13. java.lang.RuntimeException: Method setText in android.widget.TextView not mocked.
See http://g.co/androidstudio/not-mocked for details.
at android.widget.TextView.setText(TextView.java)
at lv.buzdin.alexey.MainActivityPresenterTest.test(MainActivityPresenterTest.java:39)
@Test
public void name() throws Exception {
TextView textView = new TextView(null);
textView.setText("hello");
}
17. Testable architecture
๏ Use MV* Patterns
๏ Dependency Injection is a must
๏ Try to use POJOs where possible
๏ Wrap static Android classes to Services
(Log, Toast, etc)
๏ Avoid highly coupling to android classes in *
code
18. Model - View - Whatever
(Activity/Fragment)
๏ Activity is polluted. (Lifecycle
Logic, LayoutInflater, static calls,
etc)
๏ We need a POJO
20. public class MainActivityPresenter {
…
public void initPresenter(ActionBarActivity activity) {
this.activity = activity;
ButterKnife.inject(this, activity);
}
public void initNavigationDrawer() {
activity.setSupportActionBar(toolbar);
drawerToggle = new ActionBarDrawerToggle(activity, drawerLayout, R.string.app_name, R.string.app_name) {
@Override
public void onDrawerOpened(View drawerView) {
super.onDrawerOpened(drawerView);
listView.invalidateViews(); //Refresh counter for bookmarks
}
};
drawerToggle.setDrawerIndicatorEnabled(true);
drawerLayout.setDrawerListener(drawerToggle);
activity.getSupportActionBar().setDisplayHomeAsUpEnabled(true);
activity.getSupportActionBar().setHomeButtonEnabled(true);
listView.setAdapter(navigationAdapter);
}
}
21. Testable architecture
๏ Use MV* Patterns
๏ Dependency Injection is a must
๏ Try to use POJOs where possible
๏ Wrap static Android classes to Services
(Log, Toast, etc)
๏ Avoid highly coupling to android classes in *
code
23. @Singleton
public class MainActivityPresenter {
@Inject SocialNetworkNavigationService socialsService;
@Inject SharedPrefsService preferences;
@Inject NavigationAdapter navigationAdapter;
…
public boolean firstApplicationStart() {
boolean subsequentStart = preferences.getBool(PreferencesConstants.SUBSEQUENT_START);
if (!subsequentStart) {
preferences.setBool(PreferencesConstants.SUBSEQUENT_START, true);
return true;
}
return false;
}
}
24. Testable architecture
๏ Use MV* Patterns
๏ Dependency Injection is a must
๏ Try to use POJOs where possible
๏ Wrap static Android classes to Services
(Log, Toast, etc)
๏ Avoid highly coupling to android classes in *
code
25. public class SharedPrefsService {
@Inject
public Context context;
private SharedPreferences getPrefs() {
return PreferenceManager.getDefaultSharedPreferences(context);
}
public boolean getBool(String key) {
return getPrefs().getBoolean(key, false);
}
public void setBool(String key, boolean value) {
getPrefs().edit().putBoolean(key, value).commit();
}
}
26. Testable architecture
๏ Use MV* Patterns
๏ Dependency Injection is a must
๏ Try to use POJOs where possible
๏ Wrap static Android classes to Services
(Log, Toast, etc)
๏ Avoid highly coupling to android classes in *
code
27. Removes View dependency for Whatever
Button b = (Button)findViewById(R.id.button);
b.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
b.setBackgroundColor(Red);
}
});
32. Object o = mock(Object.class);
doReturn(true).when(o).equals(any());
Object o = spy(“Hi”);
doReturn(true).when(o).equals(any());
o.hashCode() -> is real
33. @RunWith(MockitoJUnitRunner.class)
public class MyClassTest {
@InjectMocks MyFragment fragment;
@Mock Button b;
@Test
public void test() throws Exception {
fragment.clicks = Observable.just(null);
fragment.init();
verify(b).setBackgroundColor(Red);
}
}
39. JUnit Lifecycle
public class RunnerTest {
@BeforeClass public static void beforeClass() { out.println("Before Class");}
@Before public void before() { out.println("Before");}
@Test public void test() { out.println("Test"); }
@After public void after() { out.println("After"); }
@AfterClass public static void afterClass() { out.println("After Class"); }
}
40. JUnit Lifecycle
public class RunnerTest {
@BeforeClass public static void beforeClass() { out.println("Before Class");}
@Before public void before() { out.println("Before");}
@Test public void test() { out.println("Test"); }
@After public void after() { out.println("After"); }
@AfterClass public static void afterClass() { out.println("After Class"); }
}
Before Class
Before
Test
After
After Class
Process finished with exit code 0
44. @RunWith(CustomRunner.class)
public class RunnerTest {
….
}
Runner Before Class
Before Class
Runner Before
Before
Test
After
Runner After
After Class
Runner After Class
Process finished with exit code 0
AndroidJUnitRunner +
MockitoJUnitRunner +
Parametrized
45.
46. JUnit Rules
•Rules allow flexible addition of the behaviour
of each test method in a test class
•Base Rules Provided in JUnit:
Temporary Folder Rule; ExternalResource Rule;
ErrorCollector Rule; TestName Rule; Timeout Rule;
RuleChain
48. @RunWith(CustomRunner.class)
public class RunnerTest {
@ClassRule public static CustomRule classRule = new CustomRule(true);
@Rule public CustomRule rule = new CustomRule(false);
@BeforeClass public static void beforeClass() { out.println("Before Class");}
@Before public void before() { out.println("Before");}
@Test public void test() { out.println("Test"); }
@After public void after() { out.println("After"); }
@AfterClass public static void afterClass() { out.println("After Class"); }
}
49. Class Rule Before
Runner Before Class
Before Class
Rule Before
Runner Before
Before
Test
After
Runner After
Rule After
After Class
Runner After Class
Class Rule After
50. Class Rule Before
Runner Before Class
Before Class
Rule Before
Runner Before
Before
Test
After
Runner After
Rule After
After Class
Runner After Class
Class Rule After
75. Grouped Assertions
@Test
void groupedAssertions() {
// In a grouped assertion all assertions are executed, and any
// failures will be reported together.
assertAll("address",
() -> assertEquals("John", address.getFirstName()),
() -> assertEquals("User", address.getLastName())
);
}
80. in Android
• Not coming soon
• Would require a rewrite for all testing libraries
• Would require Android Studio support
• Would simplify the Extension model
https://github.com/junit-team/junit5/issues/204
81. Integration Tests
๏ Uses Robolectric framework
๏ Runs on JVM with Shadow Android SDK
๏ Has access to Context and all Android
peripheral
84. public class SharedPrefsService {
@Inject
public Context context;
private SharedPreferences getPrefs() {
return PreferenceManager.getDefaultSharedPreferences(context);
}
public boolean getBool(String key) {
return getPrefs().getBoolean(key, false);
}
public void setBool(String key, boolean value) {
getPrefs().edit().putBoolean(key, value).commit();
}
}
85. Robolectric
๏ Life saver when complex Android SDK
calls should be tested
๏ Slow compared to Unit Tests
๏ Not up to date to the latest SDKs
(API 24 not supported yet)
86. UI Tests
๏ Runs on actual Android Device
๏ Slower the Unit tests
๏ Brittle and dependant on
device health
88. Android Espresso
@Test
public void multiActivityTest() {
onView(withId(R.id.date))
.perform(click());
// Loads another activity riiiight here
onView(allOf(withId(R.id.date_expanded), withText("SomeRandomDate")))
.check(matches(isDisplayed()))
.perform(click());
// Yay! No waiting!
}
89. Espresso comes with Hamcrest integration
@Test
public void dateTest() {
onView(withId(R.id.date))
.check(matches(withText("2014-10-15")));
}
90. Robotium vs Espresso
• Espresso faster
• Robotium has bigger SDK coverage
• Espresso has built in wait mechanism that is
optimised for android lifecycle
http://www.stevenmarkford.com/android-espresso-vs-robotium-
benchmarks/
95. Cross platform tests
If you have dedicated QA team and product on multiple
platforms - go Calabash or Appium
• More flacky tests
• Less performant speed
• Some test reuse
• Easier for QA
97. How to run UI test
• Don’t initialize run-time dependencies (event
tracking, analytics, long-init things like payment
solutions)
• Don’t hit up real backend, mock out responses
• Insert appropriate test data before test starts
running
98. How to mock a Server
- Mock Server through DI
- Mock HTTP Server instance on Device
- Dev instance of Server
99. DI: Create a custom Test Runner
public class MockTestRunner extends AndroidJUnitRunner {
@Override
public Application newApplication(ClassLoader cl, String className, Context ctx)
throws InstantiationException, IllegalAccessException, ClassNotFoundException {
return super.newApplication(cl, MockDemoApplication.class.getName(), ctx);
}
}
100. DI: Create a custom Test Application
public class MockDemoApplication extends DemoApplication {
@Override
protected DemoComponent createComponent() {
return DaggerMainActivityTest_TestComponent.builder().build();
}
}
101. MockServer on Device: AndroidAsync
https://github.com/koush/AndroidAsync
AsyncHttpServer server = new AsyncHttpServer();
server.get("/", new HttpServerRequestCallback() {
@Override
public void onRequest(AsyncHttpServerRequest request,
AsyncHttpServerResponse response) {
response.send("Hello!!!");
}
});
server.listen(5000);
109. Conclusion
๏ Unit tests are cheap, make them your first
frontier
๏ Adapt code to make it more testable
๏ Structure tests with @Rules and Hamcrest
Matchers
๏ Mockito + Powermock will help to mock
Android else Robolectric will
110. Conclusion
๏ UI tests are harder to write and maintain
๏ If you have a dedicated mobile QA team
think of cross-platform tests
๏ For UI tests have a config for Mocked server
and other integration points
๏ Configure either emulator startup or device
farm on your CI