Dependency Injection for Android @ Ciklum speakers corner Kiev 29. May 2014First Tuesday Bergen
We are happy to invite you to the Speakers’ Corner today, on Thursday May 29, from 18.30 till 19.30 at SkyPoint to meet Thomas Vervik, Head of Development Bipper Communications who will talk on “How to save money on QA - Dependency Injection and automated testing on Android”
Thomas is Head of Development for Bipper Communications, and has been managing the company's team in Kiev since February 2012. Originally a seasoned Java server backend/frontend developer, he has the last two years started mobile development, first with HTML 5 and later Android.
Mobile development has since its birth around 2008 gone from simple apps to more complex enterprise similar software. The increase in size and complexity yields the need for structuring the code differently in order to handle the new complexity. The tools used to handle this complexity has been applied to server side development for years, but mobile development has been lagging behind.
But not anymore. New frameworks built on proven paradigms are emerging, and in this Speakers Corner we will introduce Dependency Injection for Android, the motivation for its use, and one of the implementations - Dagger. Dependency Injection has several advantages, but in this presentation we will focus on how it enables to write proper automated tests.
We are happy to invite you to the Speakers’ Corner today, on Thursday May 29, from 18.30 till 19.30 at SkyPoint to meet Thomas Vervik, Head of Development Bipper Communications who will talk on “How to save money on QA - Dependency Injection and automated testing on Android”
Thomas is Head of Development for Bipper Communications, and has been managing the company's team in Kiev since February 2012. Originally a seasoned Java server backend/frontend developer, he has the last two years started mobile development, first with HTML 5 and later Android.
Mobile development has since its birth around 2008 gone from simple apps to more complex enterprise similar software. The increase in size and complexity yields the need for structuring the code differently in order to handle the new complexity. The tools used to handle this complexity has been applied to server side development for years, but mobile development has been lagging behind.
But not anymore. New frameworks built on proven paradigms are emerging, and in this Speakers Corner we will introduce Dependency Injection for Android, the motivation for its use, and one of the implementations - Dagger. Dependency Injection has several advantages, but in this presentation we will focus on how it enables to write proper automated tests.
The PVS-Studio team is now actively developing a static analyzer for C# code. The first version is expected by the end of 2015. And for now my task is to write a few articles to attract C# programmers' attention to our tool in advance. I've got an updated installer today, so we can now install PVS-Studio with C#-support enabled and even analyze some source code. Without further hesitation, I decided to scan whichever program I had at hand. This happened to be the Umbraco project. Of course we can't expect too much of the current version of the analyzer, but its functionality has been enough to allow me to write this small article.
Every now and then, we have to write articles about how we've checked another fresh version of some compiler. That's not really much fun. However, as practice shows, if we stop doing that for a while, folks start doubting whether PVS-Studio is worth its title of a good catcher of bugs and vulnerabilities. What if the new compiler can do that too? Sure, compilers evolve, but so does PVS-Studio – and it proves, again and again, its ability to catch bugs even in high-quality projects such as compilers.
An important event has taken place in the PVS-Studio analyzer's life: support of C#-code analysis was added in the latest version. As one of its developers, I couldn't but try it on some project. Reading about scanning small and little-known projects is not much interesting of course, so it had to be something popular, and I picked MonoDevelop.
In May 2016, German game-development company Crytek made the, decision to upload the source code of their game engine, 'CryEngine V' to GitHub. The project is in active development, which leads to a large number of errors in the code. We have already checked the project with PVS-Studio for Windows, and now we can also analyze it using PVS-Studio for Linux. There was enough material for an article with the description of only crucial errors.
The document discusses unit testing and test-driven development. It introduces the QUnit JavaScript testing framework, describing how to write tests and assertions using its API. Key aspects covered include setting up QUnit, the test and assert functions, asynchronous testing, grouping tests into modules, and integrating automated testing with Node and Grunt.
In May 2016, German game-development company Crytek made a decision to upload the source code of their game engine CryEngine V to Github. The engine is written in C++ and has immediately attracted attention of both the open-source developer community and the team of developers of PVS-Studio static analyzer who regularly scan the code of open-source projects to estimate its quality. A lot of great games were created by a number of video-game development studios using various versions of CryEngine, and now the engine has become available to even more developers. This article gives an overview of errors found in the project by PVS-Studio static analyzer.
Dependency Injection for Android @ Ciklum speakers corner Kiev 29. May 2014First Tuesday Bergen
We are happy to invite you to the Speakers’ Corner today, on Thursday May 29, from 18.30 till 19.30 at SkyPoint to meet Thomas Vervik, Head of Development Bipper Communications who will talk on “How to save money on QA - Dependency Injection and automated testing on Android”
Thomas is Head of Development for Bipper Communications, and has been managing the company's team in Kiev since February 2012. Originally a seasoned Java server backend/frontend developer, he has the last two years started mobile development, first with HTML 5 and later Android.
Mobile development has since its birth around 2008 gone from simple apps to more complex enterprise similar software. The increase in size and complexity yields the need for structuring the code differently in order to handle the new complexity. The tools used to handle this complexity has been applied to server side development for years, but mobile development has been lagging behind.
But not anymore. New frameworks built on proven paradigms are emerging, and in this Speakers Corner we will introduce Dependency Injection for Android, the motivation for its use, and one of the implementations - Dagger. Dependency Injection has several advantages, but in this presentation we will focus on how it enables to write proper automated tests.
We are happy to invite you to the Speakers’ Corner today, on Thursday May 29, from 18.30 till 19.30 at SkyPoint to meet Thomas Vervik, Head of Development Bipper Communications who will talk on “How to save money on QA - Dependency Injection and automated testing on Android”
Thomas is Head of Development for Bipper Communications, and has been managing the company's team in Kiev since February 2012. Originally a seasoned Java server backend/frontend developer, he has the last two years started mobile development, first with HTML 5 and later Android.
Mobile development has since its birth around 2008 gone from simple apps to more complex enterprise similar software. The increase in size and complexity yields the need for structuring the code differently in order to handle the new complexity. The tools used to handle this complexity has been applied to server side development for years, but mobile development has been lagging behind.
But not anymore. New frameworks built on proven paradigms are emerging, and in this Speakers Corner we will introduce Dependency Injection for Android, the motivation for its use, and one of the implementations - Dagger. Dependency Injection has several advantages, but in this presentation we will focus on how it enables to write proper automated tests.
The PVS-Studio team is now actively developing a static analyzer for C# code. The first version is expected by the end of 2015. And for now my task is to write a few articles to attract C# programmers' attention to our tool in advance. I've got an updated installer today, so we can now install PVS-Studio with C#-support enabled and even analyze some source code. Without further hesitation, I decided to scan whichever program I had at hand. This happened to be the Umbraco project. Of course we can't expect too much of the current version of the analyzer, but its functionality has been enough to allow me to write this small article.
Every now and then, we have to write articles about how we've checked another fresh version of some compiler. That's not really much fun. However, as practice shows, if we stop doing that for a while, folks start doubting whether PVS-Studio is worth its title of a good catcher of bugs and vulnerabilities. What if the new compiler can do that too? Sure, compilers evolve, but so does PVS-Studio – and it proves, again and again, its ability to catch bugs even in high-quality projects such as compilers.
An important event has taken place in the PVS-Studio analyzer's life: support of C#-code analysis was added in the latest version. As one of its developers, I couldn't but try it on some project. Reading about scanning small and little-known projects is not much interesting of course, so it had to be something popular, and I picked MonoDevelop.
In May 2016, German game-development company Crytek made the, decision to upload the source code of their game engine, 'CryEngine V' to GitHub. The project is in active development, which leads to a large number of errors in the code. We have already checked the project with PVS-Studio for Windows, and now we can also analyze it using PVS-Studio for Linux. There was enough material for an article with the description of only crucial errors.
The document discusses unit testing and test-driven development. It introduces the QUnit JavaScript testing framework, describing how to write tests and assertions using its API. Key aspects covered include setting up QUnit, the test and assert functions, asynchronous testing, grouping tests into modules, and integrating automated testing with Node and Grunt.
In May 2016, German game-development company Crytek made a decision to upload the source code of their game engine CryEngine V to Github. The engine is written in C++ and has immediately attracted attention of both the open-source developer community and the team of developers of PVS-Studio static analyzer who regularly scan the code of open-source projects to estimate its quality. A lot of great games were created by a number of video-game development studios using various versions of CryEngine, and now the engine has become available to even more developers. This article gives an overview of errors found in the project by PVS-Studio static analyzer.
Talk was given for the first time at JPrime 2017 conference in Sofia, Bulgaria
JUnit is the standard way to test things in Java. In fact, it is the most commonly included external library for Java projects! Here is another fact - JUnit 4 release was 11 years ago and no feature releases were added in recent years. What you knew about JUnit in 2010 is still 100% relevant today. In 2017...
So finally, time for upgrade!
What took 11 years? What is new? What changed and what stayed the same? What about IDE and build tool support? When is the release date? What will testing on the JVM look like in the future? Check the presentation and you will find out.
For more info about JPrime check out jprime.io
Date Processing Attracts Bugs or 77 Defects in Qt 6Andrey Karpov
The recent Qt 6 release compelled us to recheck the framework with PVS-Studio. In this article, we reviewed various interesting errors we found, for example, those related to processing dates. The errors we discovered prove that developers can greatly benefit from regularly checking their projects with tools like PVS-Studio.
Test or Go Fishing - a guide on how to write better Swift for iOSPaul Ardeleanu
The document discusses test-driven development (TDD) and behavior-driven development (BDD). It explains that TDD relies on writing tests before code to verify requirements and that BDD combines TDD techniques with domain-driven design principles. An example of writing unit tests for a Task struct in Swift using the Xcode testing framework is provided, demonstrating the TDD process of writing a failing test, then code to pass the test, and refactoring.
Dagger is a dependency injection framework that helps manage object creation and dependencies. It allows injecting dependencies into classes rather than having them directly instantiate dependencies. This improves testability. The document discusses how Dagger is used at the New York Times, including setting up modules, components, scopes like activity scope, and testing with Dagger. Qualifiers are used to provide different implementations for different flavors. Modules provide dependencies, components compose modules and inject dependencies. This architecture allows scaling across build variants and libraries while improving testability and code organization.
Typescript fundamentals document summarized in 3 sentences:
The document discusses Typescript fundamentals including types, classes, interfaces, modules and how to use the Typescript compiler. It explains how Typescript adds type safety and compile time checking to JavaScript by using types for variables, parameters, returns and more. Examples are provided for many Typescript features and how they compile down to equivalent JavaScript.
1. The document discusses various tools and frameworks for unit testing Java, Android, and C/C++ code including JUnit, EasyMock, Google Test, and Google Mock.
2. It provides information on setting up and writing tests for each framework including creating test projects, including libraries, and using mocking functionality.
3. Code examples and references are given for writing and running unit tests with each testing framework.
The document discusses various aspects of unit testing including definitions, benefits, naming standards, and best practices. It provides definitions for terms like error, defect, failure. It outlines the benefits of unit testing like finding bugs early, enabling code refactoring. It discusses what should be tested like boundaries, error conditions. It also provides examples of good test names and guidelines for structuring and naming unit tests.
The document discusses JUnit, a unit testing framework for Java. It provides an example of using JUnit to test a class called StaticCalculation that performs basic math operations like addition and multiplication. The tests check that the operations return the expected values. It also discusses how to create JUnit tests in Eclipse and integrate test cases into source code files.
This document discusses unit testing ILE procedures in IBM i. It introduces unit testing as a way to identify bugs early and test code as it is written. It outlines how to create a test script in RPG that calls the procedures being tested and produces a report of the inputs, expected outputs, and actual results. The document provides terminology for different types of testing and guidelines for compiling test scripts separately from production code. It emphasizes that unit testing should be integrated into the development process.
Testing and Mocking Object - The Art of Mocking.Deepak Singhvi
The document provides an overview of mocking objects for unit testing. It discusses the problems with testing, such as dependencies on external objects. Mocking objects allows creating test doubles that simulate real objects' behavior for testing in isolation. The document outlines best practices for mocking, such as mocking interfaces rather than concrete classes and verifying expectations. It provides examples of using EasyMock to define mock objects and expected behavior.
An Introduction to JUnit 5 and how to use it with Spring boot tests and Mockitoshaunthomas999
This document provides an overview of JUnit 5, including its components and features. It introduces JUnit 5 as an improvement over JUnit 4, released in 2017 to work with Java 8+. JUnit 5 consists of the Platform, Jupiter, and Vintage. The Platform provides test discovery and execution. Jupiter supports writing new tests with annotations and extensions. Vintage allows running old JUnit 3 & 4 tests on the platform. New features discussed include assertions, assumptions, display names, tags, repetition, and parameterization. It also covers using JUnit 5 with Spring tests and Mockito.
Some of you may know that we have recently released version 6.00 of our analyzer, that now has C# support. The ability to scan C# projects increases the number of open-source projects we can analyze. This article is about one such check. This time it is a project, developed by Sony Computer Entertainment (SCEI).
The document provides an overview of the Android infrastructure and key concepts:
(1) It describes the layers of an Android application including the presentation layer, application logic layer, and domain layer.
(2) It explains important Android concepts such as the Android runtime environment, Dalvik virtual machine, application lifecycle and activities, and use of contexts.
(3) It discusses alternatives for common tasks like dependency injection with RoboGuice and Dagger, handling resources and views with ButterKnife and AndroidAnnotations, and accessing data with SQLite and ORMLite.
(4) It also briefly covers testing approaches on the DVM and JVM using AndroidTestCase, Robotium, and Robolectric
Test or Go Fishing - a guide on how to write better Swift for iOSPaul Ardeleanu
The document discusses test-driven development (TDD) and provides guidance on writing tests and better Swift code for iOS applications. It covers TDD principles like the feature-test-refactor cycle and testing pyramid. It also discusses testing iOS applications with XCTest and UI testing, using third-party libraries, object factories, and other tips to improve code quality and testability.
https://www.youtube.com/watch?v=9fn5s8_CYJI
Dagger is a complex tool, we can all agree on that. It's also the most performant and scalable dependency injector we have available -- no wonder it's the official recommendation from Google when it comes to dependency injection for Android apps. And yet, we keep looking for simpler alternatives (usually service locators) just so we don't have to deal with it.
Even thought Dagger is complex, it doesn't have to be complicated. It's possible to keep things simple and still take advantage of what it offers at its core. There are many ways to setup Dagger, and believe it or not, some of them are quite simple. The goal of this talk is to present a simplistic approach to Dagger, where we can take advantage of dependency injection with minimal boilerplate and optimum performance. On top of that, we'll be looking in details on best practices and how to ensure you're taking the most out of Dagger.
Join me if you've had unpleasant experiences with Dagger -- or even if you're happy with your current setup -- so we can take a fresh look on how we can work with it. And if you haven't worked with Dagger before, this is the perfect opportunity to get off on the right foot!
https://androidmakers.fr/schedule/?sessionId=YYF-6635
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 Pilsen 2016.
Virtual machines are important tools in the arsenal of a software developer. Being an active user of VirtualBox, and checking various open source projects with the help of it, I was personally interested in checking its source code. We did the first check of this project in 2014, and the description of 50 errors barely fit into two articles. With the release of Windows 10 and VirtualBox 5.0.XX the stability of the program got significantly worse, in my humble opinion. So, I decided to check the project again.
The document discusses setting up continuous integration for a JavaScript project using Jenkins. It describes configuring Jenkins to run unit tests with RhinoUnit after checking out the code from a GitHub repository. Jenkins fetches the latest code, runs the unit tests via an Ant target, and reports the results, allowing for continuous integration and automated testing of the JavaScript project.
Test or Go Fishing - A guide on how to write better Swift for iOSPaul Ardeleanu
The document discusses test-driven development (TDD) and behavior-driven development (BDD). It explains that TDD relies on writing tests before code to verify requirements and that BDD combines TDD techniques with domain-driven design principles to facilitate collaboration. An example of writing unit tests for a Task struct in Swift using the Xcode test framework is also provided.
1. The document discusses designing code for testability. It emphasizes dependency injection and mocking to easily instantiate classes and invoke methods during testing without dependencies.
2. It also discusses avoiding private and static methods when possible since they cannot be overridden or replaced, making the code harder to test. Following good design practices like the SOLID principles leads to more testable code.
3. The document provides examples of refactoring code to make it more testable through dependency injection and interfaces. This allows dependencies to be mocked or stubbed during testing and makes the code easier to extend.
The document discusses mutation testing as a way to evaluate test effectiveness beyond just code coverage metrics. It introduces the concept of mutation testing, where automated tools make small changes or "mutations" to the production code and tests are run to see if they can detect the changes. This helps identify weaknesses or gaps in test coverage. The document provides examples of mutation tools for Java and other languages and tips for getting started with mutation testing, including performance tweaking and integrating it into continuous integration pipelines. Mutation testing can help improve test quality, especially for safety critical systems, but should start small and be tweaked for performance.
Talk was given for the first time at JPrime 2017 conference in Sofia, Bulgaria
JUnit is the standard way to test things in Java. In fact, it is the most commonly included external library for Java projects! Here is another fact - JUnit 4 release was 11 years ago and no feature releases were added in recent years. What you knew about JUnit in 2010 is still 100% relevant today. In 2017...
So finally, time for upgrade!
What took 11 years? What is new? What changed and what stayed the same? What about IDE and build tool support? When is the release date? What will testing on the JVM look like in the future? Check the presentation and you will find out.
For more info about JPrime check out jprime.io
Date Processing Attracts Bugs or 77 Defects in Qt 6Andrey Karpov
The recent Qt 6 release compelled us to recheck the framework with PVS-Studio. In this article, we reviewed various interesting errors we found, for example, those related to processing dates. The errors we discovered prove that developers can greatly benefit from regularly checking their projects with tools like PVS-Studio.
Test or Go Fishing - a guide on how to write better Swift for iOSPaul Ardeleanu
The document discusses test-driven development (TDD) and behavior-driven development (BDD). It explains that TDD relies on writing tests before code to verify requirements and that BDD combines TDD techniques with domain-driven design principles. An example of writing unit tests for a Task struct in Swift using the Xcode testing framework is provided, demonstrating the TDD process of writing a failing test, then code to pass the test, and refactoring.
Dagger is a dependency injection framework that helps manage object creation and dependencies. It allows injecting dependencies into classes rather than having them directly instantiate dependencies. This improves testability. The document discusses how Dagger is used at the New York Times, including setting up modules, components, scopes like activity scope, and testing with Dagger. Qualifiers are used to provide different implementations for different flavors. Modules provide dependencies, components compose modules and inject dependencies. This architecture allows scaling across build variants and libraries while improving testability and code organization.
Typescript fundamentals document summarized in 3 sentences:
The document discusses Typescript fundamentals including types, classes, interfaces, modules and how to use the Typescript compiler. It explains how Typescript adds type safety and compile time checking to JavaScript by using types for variables, parameters, returns and more. Examples are provided for many Typescript features and how they compile down to equivalent JavaScript.
1. The document discusses various tools and frameworks for unit testing Java, Android, and C/C++ code including JUnit, EasyMock, Google Test, and Google Mock.
2. It provides information on setting up and writing tests for each framework including creating test projects, including libraries, and using mocking functionality.
3. Code examples and references are given for writing and running unit tests with each testing framework.
The document discusses various aspects of unit testing including definitions, benefits, naming standards, and best practices. It provides definitions for terms like error, defect, failure. It outlines the benefits of unit testing like finding bugs early, enabling code refactoring. It discusses what should be tested like boundaries, error conditions. It also provides examples of good test names and guidelines for structuring and naming unit tests.
The document discusses JUnit, a unit testing framework for Java. It provides an example of using JUnit to test a class called StaticCalculation that performs basic math operations like addition and multiplication. The tests check that the operations return the expected values. It also discusses how to create JUnit tests in Eclipse and integrate test cases into source code files.
This document discusses unit testing ILE procedures in IBM i. It introduces unit testing as a way to identify bugs early and test code as it is written. It outlines how to create a test script in RPG that calls the procedures being tested and produces a report of the inputs, expected outputs, and actual results. The document provides terminology for different types of testing and guidelines for compiling test scripts separately from production code. It emphasizes that unit testing should be integrated into the development process.
Testing and Mocking Object - The Art of Mocking.Deepak Singhvi
The document provides an overview of mocking objects for unit testing. It discusses the problems with testing, such as dependencies on external objects. Mocking objects allows creating test doubles that simulate real objects' behavior for testing in isolation. The document outlines best practices for mocking, such as mocking interfaces rather than concrete classes and verifying expectations. It provides examples of using EasyMock to define mock objects and expected behavior.
An Introduction to JUnit 5 and how to use it with Spring boot tests and Mockitoshaunthomas999
This document provides an overview of JUnit 5, including its components and features. It introduces JUnit 5 as an improvement over JUnit 4, released in 2017 to work with Java 8+. JUnit 5 consists of the Platform, Jupiter, and Vintage. The Platform provides test discovery and execution. Jupiter supports writing new tests with annotations and extensions. Vintage allows running old JUnit 3 & 4 tests on the platform. New features discussed include assertions, assumptions, display names, tags, repetition, and parameterization. It also covers using JUnit 5 with Spring tests and Mockito.
Some of you may know that we have recently released version 6.00 of our analyzer, that now has C# support. The ability to scan C# projects increases the number of open-source projects we can analyze. This article is about one such check. This time it is a project, developed by Sony Computer Entertainment (SCEI).
The document provides an overview of the Android infrastructure and key concepts:
(1) It describes the layers of an Android application including the presentation layer, application logic layer, and domain layer.
(2) It explains important Android concepts such as the Android runtime environment, Dalvik virtual machine, application lifecycle and activities, and use of contexts.
(3) It discusses alternatives for common tasks like dependency injection with RoboGuice and Dagger, handling resources and views with ButterKnife and AndroidAnnotations, and accessing data with SQLite and ORMLite.
(4) It also briefly covers testing approaches on the DVM and JVM using AndroidTestCase, Robotium, and Robolectric
Test or Go Fishing - a guide on how to write better Swift for iOSPaul Ardeleanu
The document discusses test-driven development (TDD) and provides guidance on writing tests and better Swift code for iOS applications. It covers TDD principles like the feature-test-refactor cycle and testing pyramid. It also discusses testing iOS applications with XCTest and UI testing, using third-party libraries, object factories, and other tips to improve code quality and testability.
https://www.youtube.com/watch?v=9fn5s8_CYJI
Dagger is a complex tool, we can all agree on that. It's also the most performant and scalable dependency injector we have available -- no wonder it's the official recommendation from Google when it comes to dependency injection for Android apps. And yet, we keep looking for simpler alternatives (usually service locators) just so we don't have to deal with it.
Even thought Dagger is complex, it doesn't have to be complicated. It's possible to keep things simple and still take advantage of what it offers at its core. There are many ways to setup Dagger, and believe it or not, some of them are quite simple. The goal of this talk is to present a simplistic approach to Dagger, where we can take advantage of dependency injection with minimal boilerplate and optimum performance. On top of that, we'll be looking in details on best practices and how to ensure you're taking the most out of Dagger.
Join me if you've had unpleasant experiences with Dagger -- or even if you're happy with your current setup -- so we can take a fresh look on how we can work with it. And if you haven't worked with Dagger before, this is the perfect opportunity to get off on the right foot!
https://androidmakers.fr/schedule/?sessionId=YYF-6635
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 Pilsen 2016.
Virtual machines are important tools in the arsenal of a software developer. Being an active user of VirtualBox, and checking various open source projects with the help of it, I was personally interested in checking its source code. We did the first check of this project in 2014, and the description of 50 errors barely fit into two articles. With the release of Windows 10 and VirtualBox 5.0.XX the stability of the program got significantly worse, in my humble opinion. So, I decided to check the project again.
The document discusses setting up continuous integration for a JavaScript project using Jenkins. It describes configuring Jenkins to run unit tests with RhinoUnit after checking out the code from a GitHub repository. Jenkins fetches the latest code, runs the unit tests via an Ant target, and reports the results, allowing for continuous integration and automated testing of the JavaScript project.
Test or Go Fishing - A guide on how to write better Swift for iOSPaul Ardeleanu
The document discusses test-driven development (TDD) and behavior-driven development (BDD). It explains that TDD relies on writing tests before code to verify requirements and that BDD combines TDD techniques with domain-driven design principles to facilitate collaboration. An example of writing unit tests for a Task struct in Swift using the Xcode test framework is also provided.
1. The document discusses designing code for testability. It emphasizes dependency injection and mocking to easily instantiate classes and invoke methods during testing without dependencies.
2. It also discusses avoiding private and static methods when possible since they cannot be overridden or replaced, making the code harder to test. Following good design practices like the SOLID principles leads to more testable code.
3. The document provides examples of refactoring code to make it more testable through dependency injection and interfaces. This allows dependencies to be mocked or stubbed during testing and makes the code easier to extend.
The document discusses mutation testing as a way to evaluate test effectiveness beyond just code coverage metrics. It introduces the concept of mutation testing, where automated tools make small changes or "mutations" to the production code and tests are run to see if they can detect the changes. This helps identify weaknesses or gaps in test coverage. The document provides examples of mutation tools for Java and other languages and tips for getting started with mutation testing, including performance tweaking and integrating it into continuous integration pipelines. Mutation testing can help improve test quality, especially for safety critical systems, but should start small and be tweaked for performance.
TDD is a design technique where tests are written before code to determine requirements. The Red-Green-Refactor process is followed: 1) Write a test that fails (red), 2) Write minimum code to pass the test (green), 3) Refactor code. TDD ensures quality, keeps code simple and testable, and allows for rapid change. Writing tests first helps design by clarifying requirements and preventing bugs.
In this session, you will enter the world of mutation testing. By generating mutants, that is, faulty versions of your code, you can measure how well your tests can detect bugs. You will learn about mutation tools, how they work, and how to get started, as well as when you should consider mutation testing. Want better code that is well tested? Come to this session!
TDD is now mainstream but a lot people don't know or don't remember what is its purpose. TDD is about software design not testing or catching bug. TDD helps developers to shape and create software with "good" design, what is a "good" design is something that we will discuss in the topic.
This document provides an agenda and overview for a mobile agile testing workshop covering both Android and iOS testing. The Android section covers unit, UI, and API testing tools like JUnit, Espresso, and Postman. It also discusses test-driven development. The iOS section similarly covers unit testing with XCTest, UI testing with XCUI, mocking with Cuckoo, and tools like Postman and Jenkins. The document emphasizes why testing is important for catching bugs, making changes confidently, and extending the lifespan of codebases.
The document discusses unit testing in Grails using the Spock testing framework. It covers the basics of unit testing including goals, advantages, and challenges. It then provides an overview of Spock and examples of writing unit tests in Spock including mocking methods, domains, configurations, and dependencies. The document also discusses how to write unit tests for controllers and integration tests in Grails using Spock.
The document discusses integrating security testing into the typical iterative development lifecycle through automated software tests at various stages, including unit tests, integration tests, and acceptance tests. It provides examples of using JUnit for unit testing and tools like Cactus, Selenium, and WATIR for integration and acceptance testing to validate valid/invalid inputs and test for vulnerabilities like SQL injection and cross-site scripting.
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.
This document discusses best practices for writing clean tests, including naming conventions, test structure, and principles such as keeping tests focused on individual behaviors, avoiding logic in tests, and preferring to test public APIs over private methods. It recommends giving tests clear and descriptive names, using a Given-When-Then structure, and creating reusable helper functions to prepare test data. Tests should have a single assert per scenario and verify only the relevant method arguments for the behavior being tested. Following these guidelines helps produce tests that are easy to understand and maintain.
The document provides an introduction to JUnit and Mockito frameworks for testing in Java. It covers key topics such as:
- What JUnit and Mockito are and how they are used for testing Java code
- Common JUnit annotations like @Test and how to structure test classes
- How to make assertions in JUnit tests to validate expected outcomes
- How to use Mockito to mock dependencies and define stubbed behavior
- Hands-on examples are provided to demonstrate writing tests with JUnit and Mockito
GlobalLogic Test Automation Online TechTalk “Test Driven Development as a Per...GlobalLogic Ukraine
16 грудня 2021 року відбувся GlobalLogic Test Automation Online TechTalk “Test Driven Development as a Personal Skill”! Анатолій Сахно (Software Testing Consultant, GlobalLogic) розібрав принципи TDD (розробки, керованої тестами) та приклади їх застосування. Крім того, поговорили про:
- Ефективне використання модульних тестів у повсякденних задачах;
- Використання TDD при розробці тестових фреймворків;
- Застосування принципів TDD при написанні функціональних автотестів.
Більше про захід: https://www.globallogic.com/ua/about/events/globallogic-test-automation-online-techtalk-test-driven-development-as-a-personal-skill/
Приємного перегляду і не забудьте залишити коментар про враження від TechTalk!
Ця активність — частина заходів в рамках GlobalLogic Test Automation Advent Calendar, ще більше заходів та цікавинок за посиланням: https://bit.ly/AdventCalendar_fb
Support slides for the test automation workshop realized at the iMasters Android DevConference 2015 at São Paulo. The workshop focus was around Unit Tests with JUnit, UI Tests with Espresso and UIAutomator and Testing your app in the cloud with Testdroid.
Mutation Analysis for JavaScript Web Applicaiton Testing SEKE2013nkazuki
This slide is for a presentation at the 25th International Conference on Software Engineering and Knowledge Engineering (SEKE'13) at Boston.
Abstract of the published paper:
When developers test modern web applications that use JavaScript, challenging issues lie in their event-driven, asynchronous, and dynamic features. Many researchers have assessed the adequacy of test cases with code coverage criteria; however, in this paper, we show that the code coverage-based approach possibly misses some faults in the applications. We propose a mutation analysis approach for estimating the fault-finding capability of test cases. We assume that developers can find overlooked fault instances and improve the test cases with the estimated capability. To create a set of faulty programs, i.e., mutants, we classify the JavaScript features in web applications and then define a comprehensive set of mutation operators. We conducted a case study on a real-world application and found that our approach supported the improvement of test cases to expose hand-seeded faults by an extra ten percent.
You can find the transcript used in the presentation from the link below:
https://docs.google.com/document/d/1CsqcYKyHZQL6Z7OkM_LVVyB-aMURMWl37lc03LOa4fI/edit?usp=sharing
Unit testing involves testing individual units or components of an application to ensure they operate as expected. The UnitTest++ and HippoMocks frameworks allow writing and running unit tests in C++. UnitTest++ provides macros and functions to define tests and make assertions while HippoMocks allows mocking dependencies to isolate units during testing.
This document discusses testability and provides lessons learned around testability. It begins with an introduction of the speaker and their background in testing. It then outlines some common testability problems like statics, singletons, and tight coupling. Solutions discussed include dependency injection and using mocks/fakes to isolate units for testing. The document provides an example of refactoring a weather application to make it more testable and enables the use of mocks for testing.
Unit testing involves testing the smallest parts of an application individually, like testing a Calculator class's add and divide functions. Tests are written in a test class using an AAA pattern of Arrange, Act, Assert. Common assertions include assertEqual, assertTrue, assertFalse. Tests can be run from an IDE or command line and output passed/failed results. Writing tests is important for long term quality, confidence in refactoring, and enabling continuous integration. Developers are responsible for writing unit tests for their own code, with a target of around 70% code coverage.
Similar to The real beginner's guide to android testing (20)
Unlock the Future of Search with MongoDB Atlas_ Vector Search Unleashed.pdfMalak Abu Hammad
Discover how MongoDB Atlas and vector search technology can revolutionize your application's search capabilities. This comprehensive presentation covers:
* What is Vector Search?
* Importance and benefits of vector search
* Practical use cases across various industries
* Step-by-step implementation guide
* Live demos with code snippets
* Enhancing LLM capabilities with vector search
* Best practices and optimization strategies
Perfect for developers, AI enthusiasts, and tech leaders. Learn how to leverage MongoDB Atlas to deliver highly relevant, context-aware search results, transforming your data retrieval process. Stay ahead in tech innovation and maximize the potential of your applications.
#MongoDB #VectorSearch #AI #SemanticSearch #TechInnovation #DataScience #LLM #MachineLearning #SearchTechnology
5th LF Energy Power Grid Model Meet-up SlidesDanBrown980551
5th Power Grid Model Meet-up
It is with great pleasure that we extend to you an invitation to the 5th Power Grid Model Meet-up, scheduled for 6th June 2024. This event will adopt a hybrid format, allowing participants to join us either through an online Mircosoft Teams session or in person at TU/e located at Den Dolech 2, Eindhoven, Netherlands. The meet-up will be hosted by Eindhoven University of Technology (TU/e), a research university specializing in engineering science & technology.
Power Grid Model
The global energy transition is placing new and unprecedented demands on Distribution System Operators (DSOs). Alongside upgrades to grid capacity, processes such as digitization, capacity optimization, and congestion management are becoming vital for delivering reliable services.
Power Grid Model is an open source project from Linux Foundation Energy and provides a calculation engine that is increasingly essential for DSOs. It offers a standards-based foundation enabling real-time power systems analysis, simulations of electrical power grids, and sophisticated what-if analysis. In addition, it enables in-depth studies and analysis of the electrical power grid’s behavior and performance. This comprehensive model incorporates essential factors such as power generation capacity, electrical losses, voltage levels, power flows, and system stability.
Power Grid Model is currently being applied in a wide variety of use cases, including grid planning, expansion, reliability, and congestion studies. It can also help in analyzing the impact of renewable energy integration, assessing the effects of disturbances or faults, and developing strategies for grid control and optimization.
What to expect
For the upcoming meetup we are organizing, we have an exciting lineup of activities planned:
-Insightful presentations covering two practical applications of the Power Grid Model.
-An update on the latest advancements in Power Grid -Model technology during the first and second quarters of 2024.
-An interactive brainstorming session to discuss and propose new feature requests.
-An opportunity to connect with fellow Power Grid Model enthusiasts and users.
GraphRAG for Life Science to increase LLM accuracyTomaz Bratanic
GraphRAG for life science domain, where you retriever information from biomedical knowledge graphs using LLMs to increase the accuracy and performance of generated answers
Building Production Ready Search Pipelines with Spark and MilvusZilliz
Spark is the widely used ETL tool for processing, indexing and ingesting data to serving stack for search. Milvus is the production-ready open-source vector database. In this talk we will show how to use Spark to process unstructured data to extract vector representations, and push the vectors to Milvus vector database for search serving.
UiPath Test Automation using UiPath Test Suite series, part 6DianaGray10
Welcome to UiPath Test Automation using UiPath Test Suite series part 6. In this session, we will cover Test Automation with generative AI and Open AI.
UiPath Test Automation with generative AI and Open AI webinar offers an in-depth exploration of leveraging cutting-edge technologies for test automation within the UiPath platform. Attendees will delve into the integration of generative AI, a test automation solution, with Open AI advanced natural language processing capabilities.
Throughout the session, participants will discover how this synergy empowers testers to automate repetitive tasks, enhance testing accuracy, and expedite the software testing life cycle. Topics covered include the seamless integration process, practical use cases, and the benefits of harnessing AI-driven automation for UiPath testing initiatives. By attending this webinar, testers, and automation professionals can gain valuable insights into harnessing the power of AI to optimize their test automation workflows within the UiPath ecosystem, ultimately driving efficiency and quality in software development processes.
What will you get from this session?
1. Insights into integrating generative AI.
2. Understanding how this integration enhances test automation within the UiPath platform
3. Practical demonstrations
4. Exploration of real-world use cases illustrating the benefits of AI-driven test automation for UiPath
Topics covered:
What is generative AI
Test Automation with generative AI and Open AI.
UiPath integration with generative AI
Speaker:
Deepak Rai, Automation Practice Lead, Boundaryless Group and UiPath MVP
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdfChart Kalyan
A Mix Chart displays historical data of numbers in a graphical or tabular form. The Kalyan Rajdhani Mix Chart specifically shows the results of a sequence of numbers over different periods.
Let's Integrate MuleSoft RPA, COMPOSER, APM with AWS IDP along with Slackshyamraj55
Discover the seamless integration of RPA (Robotic Process Automation), COMPOSER, and APM with AWS IDP enhanced with Slack notifications. Explore how these technologies converge to streamline workflows, optimize performance, and ensure secure access, all while leveraging the power of AWS IDP and real-time communication via Slack notifications.
AI 101: An Introduction to the Basics and Impact of Artificial IntelligenceIndexBug
Imagine a world where machines not only perform tasks but also learn, adapt, and make decisions. This is the promise of Artificial Intelligence (AI), a technology that's not just enhancing our lives but revolutionizing entire industries.
Monitoring and Managing Anomaly Detection on OpenShift.pdfTosin Akinosho
Monitoring and Managing Anomaly Detection on OpenShift
Overview
Dive into the world of anomaly detection on edge devices with our comprehensive hands-on tutorial. This SlideShare presentation will guide you through the entire process, from data collection and model training to edge deployment and real-time monitoring. Perfect for those looking to implement robust anomaly detection systems on resource-constrained IoT/edge devices.
Key Topics Covered
1. Introduction to Anomaly Detection
- Understand the fundamentals of anomaly detection and its importance in identifying unusual behavior or failures in systems.
2. Understanding Edge (IoT)
- Learn about edge computing and IoT, and how they enable real-time data processing and decision-making at the source.
3. What is ArgoCD?
- Discover ArgoCD, a declarative, GitOps continuous delivery tool for Kubernetes, and its role in deploying applications on edge devices.
4. Deployment Using ArgoCD for Edge Devices
- Step-by-step guide on deploying anomaly detection models on edge devices using ArgoCD.
5. Introduction to Apache Kafka and S3
- Explore Apache Kafka for real-time data streaming and Amazon S3 for scalable storage solutions.
6. Viewing Kafka Messages in the Data Lake
- Learn how to view and analyze Kafka messages stored in a data lake for better insights.
7. What is Prometheus?
- Get to know Prometheus, an open-source monitoring and alerting toolkit, and its application in monitoring edge devices.
8. Monitoring Application Metrics with Prometheus
- Detailed instructions on setting up Prometheus to monitor the performance and health of your anomaly detection system.
9. What is Camel K?
- Introduction to Camel K, a lightweight integration framework built on Apache Camel, designed for Kubernetes.
10. Configuring Camel K Integrations for Data Pipelines
- Learn how to configure Camel K for seamless data pipeline integrations in your anomaly detection workflow.
11. What is a Jupyter Notebook?
- Overview of Jupyter Notebooks, an open-source web application for creating and sharing documents with live code, equations, visualizations, and narrative text.
12. Jupyter Notebooks with Code Examples
- Hands-on examples and code snippets in Jupyter Notebooks to help you implement and test anomaly detection models.
Cosa hanno in comune un mattoncino Lego e la backdoor XZ?Speck&Tech
ABSTRACT: A prima vista, un mattoncino Lego e la backdoor XZ potrebbero avere in comune il fatto di essere entrambi blocchi di costruzione, o dipendenze di progetti creativi e software. La realtà è che un mattoncino Lego e il caso della backdoor XZ hanno molto di più di tutto ciò in comune.
Partecipate alla presentazione per immergervi in una storia di interoperabilità, standard e formati aperti, per poi discutere del ruolo importante che i contributori hanno in una comunità open source sostenibile.
BIO: Sostenitrice del software libero e dei formati standard e aperti. È stata un membro attivo dei progetti Fedora e openSUSE e ha co-fondato l'Associazione LibreItalia dove è stata coinvolta in diversi eventi, migrazioni e formazione relativi a LibreOffice. In precedenza ha lavorato a migrazioni e corsi di formazione su LibreOffice per diverse amministrazioni pubbliche e privati. Da gennaio 2020 lavora in SUSE come Software Release Engineer per Uyuni e SUSE Manager e quando non segue la sua passione per i computer e per Geeko coltiva la sua curiosità per l'astronomia (da cui deriva il suo nickname deneb_alpha).
HCL Notes und Domino Lizenzkostenreduzierung in der Welt von DLAUpanagenda
Webinar Recording: https://www.panagenda.com/webinars/hcl-notes-und-domino-lizenzkostenreduzierung-in-der-welt-von-dlau/
DLAU und die Lizenzen nach dem CCB- und CCX-Modell sind für viele in der HCL-Community seit letztem Jahr ein heißes Thema. Als Notes- oder Domino-Kunde haben Sie vielleicht mit unerwartet hohen Benutzerzahlen und Lizenzgebühren zu kämpfen. Sie fragen sich vielleicht, wie diese neue Art der Lizenzierung funktioniert und welchen Nutzen sie Ihnen bringt. Vor allem wollen Sie sicherlich Ihr Budget einhalten und Kosten sparen, wo immer möglich. Das verstehen wir und wir möchten Ihnen dabei helfen!
Wir erklären Ihnen, wie Sie häufige Konfigurationsprobleme lösen können, die dazu führen können, dass mehr Benutzer gezählt werden als nötig, und wie Sie überflüssige oder ungenutzte Konten identifizieren und entfernen können, um Geld zu sparen. Es gibt auch einige Ansätze, die zu unnötigen Ausgaben führen können, z. B. wenn ein Personendokument anstelle eines Mail-Ins für geteilte Mailboxen verwendet wird. Wir zeigen Ihnen solche Fälle und deren Lösungen. Und natürlich erklären wir Ihnen das neue Lizenzmodell.
Nehmen Sie an diesem Webinar teil, bei dem HCL-Ambassador Marc Thomas und Gastredner Franz Walder Ihnen diese neue Welt näherbringen. Es vermittelt Ihnen die Tools und das Know-how, um den Überblick zu bewahren. Sie werden in der Lage sein, Ihre Kosten durch eine optimierte Domino-Konfiguration zu reduzieren und auch in Zukunft gering zu halten.
Diese Themen werden behandelt
- Reduzierung der Lizenzkosten durch Auffinden und Beheben von Fehlkonfigurationen und überflüssigen Konten
- Wie funktionieren CCB- und CCX-Lizenzen wirklich?
- Verstehen des DLAU-Tools und wie man es am besten nutzt
- Tipps für häufige Problembereiche, wie z. B. Team-Postfächer, Funktions-/Testbenutzer usw.
- Praxisbeispiele und Best Practices zum sofortigen Umsetzen
Ivanti’s Patch Tuesday breakdown goes beyond patching your applications and brings you the intelligence and guidance needed to prioritize where to focus your attention first. Catch early analysis on our Ivanti blog, then join industry expert Chris Goettl for the Patch Tuesday Webinar Event. There we’ll do a deep dive into each of the bulletins and give guidance on the risks associated with the newly-identified vulnerabilities.
Introduction of Cybersecurity with OSS at Code Europe 2024Hiroshi SHIBATA
I develop the Ruby programming language, RubyGems, and Bundler, which are package managers for Ruby. Today, I will introduce how to enhance the security of your application using open-source software (OSS) examples from Ruby and RubyGems.
The first topic is CVE (Common Vulnerabilities and Exposures). I have published CVEs many times. But what exactly is a CVE? I'll provide a basic understanding of CVEs and explain how to detect and handle vulnerabilities in OSS.
Next, let's discuss package managers. Package managers play a critical role in the OSS ecosystem. I'll explain how to manage library dependencies in your application.
I'll share insights into how the Ruby and RubyGems core team works to keep our ecosystem safe. By the end of this talk, you'll have a better understanding of how to safeguard your code.
Digital Marketing Trends in 2024 | Guide for Staying AheadWask
https://www.wask.co/ebooks/digital-marketing-trends-in-2024
Feeling lost in the digital marketing whirlwind of 2024? Technology is changing, consumer habits are evolving, and staying ahead of the curve feels like a never-ending pursuit. This e-book is your compass. Dive into actionable insights to handle the complexities of modern marketing. From hyper-personalization to the power of user-generated content, learn how to build long-term relationships with your audience and unlock the secrets to success in the ever-shifting digital landscape.
Taking AI to the Next Level in Manufacturing.pdfssuserfac0301
Read Taking AI to the Next Level in Manufacturing to gain insights on AI adoption in the manufacturing industry, such as:
1. How quickly AI is being implemented in manufacturing.
2. Which barriers stand in the way of AI adoption.
3. How data quality and governance form the backbone of AI.
4. Organizational processes and structures that may inhibit effective AI adoption.
6. Ideas and approaches to help build your organization's AI strategy.
HCL Notes and Domino License Cost Reduction in the World of DLAUpanagenda
Webinar Recording: https://www.panagenda.com/webinars/hcl-notes-and-domino-license-cost-reduction-in-the-world-of-dlau/
The introduction of DLAU and the CCB & CCX licensing model caused quite a stir in the HCL community. As a Notes and Domino customer, you may have faced challenges with unexpected user counts and license costs. You probably have questions on how this new licensing approach works and how to benefit from it. Most importantly, you likely have budget constraints and want to save money where possible. Don’t worry, we can help with all of this!
We’ll show you how to fix common misconfigurations that cause higher-than-expected user counts, and how to identify accounts which you can deactivate to save money. There are also frequent patterns that can cause unnecessary cost, like using a person document instead of a mail-in for shared mailboxes. We’ll provide examples and solutions for those as well. And naturally we’ll explain the new licensing model.
Join HCL Ambassador Marc Thomas in this webinar with a special guest appearance from Franz Walder. It will give you the tools and know-how to stay on top of what is going on with Domino licensing. You will be able lower your cost through an optimized configuration and keep it low going forward.
These topics will be covered
- Reducing license cost by finding and fixing misconfigurations and superfluous accounts
- How do CCB and CCX licenses really work?
- Understanding the DLAU tool and how to best utilize it
- Tips for common problem areas, like team mailboxes, functional/test users, etc
- Practical examples and best practices to implement right away
How to Get CNIC Information System with Paksim Ga.pptxdanishmna97
Pakdata Cf is a groundbreaking system designed to streamline and facilitate access to CNIC information. This innovative platform leverages advanced technology to provide users with efficient and secure access to their CNIC details.
2. About myself
● Software Engineer at Grab
● DragonBall fan (Vegeta fan)
● @ericntd (LinkedIn, Medium, Github, StackoverFlow, Twitter)
● Send me your resume eric.nguyen at grab.com - https://grab.careers/
#droidconvn
3. My journey with unit testing
Before unit tests With unit tests
#droidconvn
@ericntd
4. Agenda
1. Why write tests
2. Types of tests
3. Introduction to unit testing
4. Challenge to unit testing with Android
5. The solution
6. Steps to your first Android unit tests
7. MVP architecture limitations
8. Q & A
@ericntd
5. 1) Why write tests?
● Improve and maintain product quality with less QA’s manual effort
● Increase confidence when shipping
● Perform routine exhaustive checks humans can’t perform, fast
● Help you write more modular code
@ericntd
6. 2) Different of type of tests
Unit tests
Component/
Integration Tests
End-to-
end
tests
20-30 mins to run
100++ component UI
tests
<10 mins to run 4000 tests
Fast to run,
easy to write,
run and to
measure
coverage
Slow to run,
difficult to
write, run and
to measure
coverage
#droidconvn
@ericntd
7. 3) Unit testing crash course
public class Calculator {
/**
* @param input an integer in the range of
[Integer.MIN_VALUE/2, Integer.MAX_VALUE/2]
* @return -1 if the input is too big or too small, otherwise the
input times 2
*/
public int timesTwo(int input) {
if (input > Integer.MAX_VALUE / 2 || input <
Integer.MIN_VALUE / 2) {
return -1;
}
return input * 2;
}
}
● We have a Calculator class with a
single timesTwo method
● The timesTwo method returns the
input times 2, except for in the
case of overflow, it returns -1
@ericntd
8. 3) Unit testing crash course
dependencies {
//...
testImplementation 'junit:junit:4.12'
testImplementation "org.mockito:mockito-core:2.12.0"
}
app/build.gradle
#droidconvn
public class CalculatorTest {
private Calculator calculator = new Calculator();
@Test
public void plusTwo() {
Assert.assertEquals(0, calculator.timesTwo(0));
Assert.assertEquals(2, calculator.timesTwo(1));
}
}
app/src/test/java/your.package.name
@ericntd
11. 3) Unit testing crash course
● Unit tests help our app’s stability
@ericntd
12. 3) Unit testing crash course
Unit tests also force us to write modular code
“The first rule of functions is that they should be small. The second
rule of functions is that they should be smaller than that. Functions
should not be 100 lines long. Functions should hardly ever be 20
lines long.” - Clean Code
@ericntd
13. 4) Challenge of unit testing in Android
● Consider a simple activity:
○ A TextView display a number, starting from 1
○ A Button named “Time Two”
● The doubling logic is from our Calculator’s
timesTwo
@ericntd
14. 4) Challenge of unit testing in Android
public class CalculatorActivity extends AppCompatActivity {
`
public Calculator calculator;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_calculator);
calculator = new Calculator();
final TextView tvNumber = findViewById(R.id.tv_number);
Button ctaTimesTwo = findViewById(R.id.cta_times_two);
ctaTimesTwo.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
updateNumber(tvNumber);
}
});
}
public void updateNumber(TextView tvNumber) {
tvNumber.setText(calculator.timesTwo(Integer.valueOf(tvNumber.getText().toString())));
}
}
CalculatorActivity is the
Controller in a Model-View-
Controller
@ericntd
15. 4) Challenge of unit testing in Android
public class CalculatorActivity extends AppCompatActivity {
public Calculator calculator;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_calculator);
calculator = new Calculator();
final TextView tvNumber = findViewById(R.id.tv_number);
Button ctaTimesTwo = findViewById(R.id.cta_times_two);
ctaTimesTwo.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
updateNumber(tvNumber);
}
});
}
public void updateNumber(TextView tvNumber) {
tvNumber.setText(calculator.timesTwo(Integer.valueOf(tvNumber.getText().toString())));
}
}
Doubling logic is based on
Calculator’s timesTwo
@ericntd
16. 4) Challenge of unit testing in Android
public class CalculatorActivityTest {
private CalculatorActivity activity = new CalculatorActivity();
@Test
public void updateNumber() {
// Preparation
TextView tvNumber = Mockito.mock(TextView.class);
Mockito.doReturn("1").when(tvNumber).getText();
// Trigger
activity.updateNumber(tvNumber);
// Validation
Assert.assertEquals("2", tvNumber.getText().toString());
Mockito.verify(tvNumber).setText(2);
}
}
● Prepare any dependency incl.
Android-specific easily
● Verify a method is called on a
mocked object
@ericntd
17. 4) Challenge of unit testing in Android
We run CalculatorActivityTest and we
get a NullPointerException.
Explanation:
The Calculator object was instantiated inside the
Activity’s onCreate method.
In our JUnit test, we have no control over the
CalculatorActivity’s onCreate method
Conclusion:
We are unable to unit test our business logics
inside an Android Activity
@ericntd
18. 4) Challenge of unit testing in Android
Possible Workarounds:
● Instantiate a Calculator object inside
updateNumber method itself
○ Inefficiency - multiple
Calculator objects instead of
reusing one
● Create a setter in the the activity:
setCalculator(Caculator)
○ Side effects e.g. race
condition, unexpected
behaviours
@ericntd
19. 5) Solution for unit testing in Android
● We need to move our business logics outside of the Activity or Fragment
● We need to refactor our app from MVC to a better architecture such as
Model-View-Presenter (MVP)
@ericntd
20. 5) Solution for unit testing in Android - Architectures
#droidconvn
● Difficult to test logics within Activity/
Fragment
● Activity/ Fragment are bloated
Model-View-Presenter
View (Fragment/
Activity)
Presenter
Activity/ Fragment
Model-View-Controller
Controller
View
● Business logics easily tested
● Activity/ Fragment much thinner without
business logics
@ericntd
21. 6) Steps to your first Android unit tests
A. Refactor your app to MVP
B. Write tests for your Presenter (contains business logics)
C. Profit!
#droidconvn
@ericntd
23. A)MVC => MVP
+
#droidconvn
public class MainActivity extends AppCompatActivity {
//...
private void searchGitHubRepos(GitHubApi gitHubApi, String query) {
gitHubApi.searchRepos(query).enqueue(new
Callback<SearchResponse>() {
@Override
public void onResponse(Call<SearchResponse> call,
Response<SearchResponse> response) {
handleResponse(response);
}
@Override
public void onFailure(Call<SearchResponse> call,
Throwable t) {
handleError("E103 - System error");
}
});
}
}
Original MainActivity in a MVC
settings. 2 business logics
methods:
● searchGitHubRepos
● handleSearchGitHubResp
onse
We will move these 2 methods
into the Presenter class
@ericntd
24. A)MVC => MVP
public class SearchPresenter implements SearchPresenterContract,
GitHubRepository
.GitHubRepositoryCallback {
private final SearchViewContract viewContract;
private final GitHubRepository repository;
//...
@Override
public void searchGitHubRepos(@Nullable final String query) {
if (query != null && query.length() > 0) {
repository.searchRepos(query, this);
}
}
}
The Presenter now contains
the 2 business logics methods:
● searchGitHubRepos
● handleSearchGitHubResp
onse
@ericntd
25. A)MVC => MVP
public class MainActivity extends AppCompatActivity implements SearchViewContract {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//...
}
@Override
public void displaySearchResults(@NonNull List<SearchResult> searchResults,
@Nullable Integer totalCount) {
rvAdapter.updateResults(searchResults);
tvStatus.setText(String.format(Locale.US, "Number of results: %d", totalCount));
}
@Override
public void displayError() {
Toast.makeText(this, "some error happened", Toast.LENGTH_SHORT).show();
}
@Override
public void displayError(String s) {
Toast.makeText(this, s, Toast.LENGTH_SHORT).show();
}
Our new Activity is much
cleaner with only ~50 lines of
code
@ericntd
26. B) Write tests for Presenter - Setup
package tech.ericntd.githubsearch.search;
public class SearchPresenterTest {
private SearchPresenter presenter;
@Mock
private GitHubRepository repository;
@Mock
private SearchViewContract viewContract;
@Before
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);// required for the "@Mock" annotations
// Make presenter a mock while using mock repository and viewContract
created above
presenter = Mockito.spy(new SearchPresenter(viewContract, repository));
}
// The tests
}
dependencies {
//...
testImplementation 'junit:junit:4.12'
testImplementation "org.mockito:mockito-core:2.12.0"
}
app/build.gradle app/src/test/java/
● Pure JUnit test
#droidconvn
@ericntd
27. B) Write test for Presenter - Example
package tech.ericntd.githubsearch.search;
public class SearchPresenterTest {
@Test
public void searchGitHubRepos() {
String searchQuery = "some query";
// Trigger
presenter.searchGitHubRepos(searchQuery);
// Validation
Mockito.verify(repository,
Mockito.times(1)).searchRepos(searchQuery,
presenter);
}
}
package tech.ericntd.githubsearch.search;
public class SearchPresenter implements
SearchPresenterContract,
GitHubRepository.GitHubRepositoryCallback {
@Override
public void searchGitHubRepos(@Nullable final String
query) {
if (query != null && query.length() > 0) {
repository.searchRepos(query, this);
}
}
}
#droidconvn
@ericntd
28. B) Write test for Presenter - Example
package tech.ericntd.githubsearch.search;
public class SearchPresenterTest {
@Test
public void searchGitHubRepos() {
String searchQuery = "some query";
// Trigger
presenter.searchGitHubRepos(searchQuery);
// Validation
Mockito.verify(repository,
Mockito.times(1)).searchRepos(searchQuery,
presenter);
}
}
package tech.ericntd.githubsearch.search;
public class SearchPresenter implements
SearchPresenterContract,
GitHubRepository.GitHubRepositoryCallback {
@Override
public void searchGitHubRepos(@Nullable final String
query) {
if (query != null && query.length() > 0) {
repository.searchRepos(query, this);
}
}
}
#droidconvn
@ericntd
29. B) Write test for Presenter - Example
package tech.ericntd.githubsearch.search;
public class SearchPresenterTest {
@Test
public void searchGitHubRepos() {
String searchQuery = "some query";
// Trigger
presenter.searchGitHubRepos(searchQuery);
// Validation
Mockito.verify(repository,
Mockito.times(1)).searchRepos(searchQuery,
presenter);
}
}
package tech.ericntd.githubsearch.search;
public class SearchPresenter implements
SearchPresenterContract,
GitHubRepository.GitHubRepositoryCallback {
@Override
public void searchGitHubRepos(@Nullable final String
query) {
if (query != null && query.length() > 0) {
repository.searchRepos(query, this);
}
}
}
#droidconvn
@ericntd
30. B) Write test for Presenter - Example
package tech.ericntd.githubsearch.search;
public class SearchPresenterTest {
@Test
public void searchGitHubRepos() {
String searchQuery = "some query";
// Trigger
presenter.searchGitHubRepos(searchQuery);
// Validation
Mockito.verify(repository,
Mockito.times(1)).searchRepos(searchQuery,
presenter);
}
}
package tech.ericntd.githubsearch.search;
public class SearchPresenter implements
SearchPresenterContract,
GitHubRepository.GitHubRepositoryCallback {
@Override
public void searchGitHubRepos(@Nullable final String
query) {
if (query != null && query.length() > 0) {
repository.searchRepos(query, this);
}
}
}
app/src/test/java/ app/src/main/java/
#droidconvn
@ericntd
36. 7) MVP architecture limitations
public class MainActivity extends AppCompatActivity
implements SearchViewContract {
// ...
@Override
public void displaySearchResults(@NonNull
List<SearchResult> searchResults,
@Nullable Integer totalCount) {
rvAdapter.updateResults(searchResults);
tvStatus.setText(String.format(Locale.US, "Number of
results: %d", totalCount));
}
}
It looks like logic, but
why is it in the View/
Activity?
#droidconvn
@ericntd
37. 7) MVP architecture limitations
● Real 70-line-function in
production code
● 4 functions like this in the same
Activity
● 200+ lines of “setText” and
“setVisibility” and co.
● Hundreds of lines of code
required in test class
● Dozens of Mockito mocks
required in test class ⇒
significantly higher test run time
#droidconvn
@ericntd
43. Android testing articles series
Part 1: A beginner’s guide to automated (unit) testing (today’s talk)
Part 2: Better tests with MVVM + data binding
Part 3: Component UI tests with Espresso from 0 to 1
#droidconvn
@ericntd
46. Thank you
@ericntd
● @ericntd (LinkedIn, Medium, Github, StackoverFlow, Twitter)
● Send me your resume eric.nguyen at grab.com -
https://grab.careers/
Editor's Notes
Ask me a question at the end for 70k GrabPay credit
They say money can’t buy happiness, I’m pretty sure it can
E.g. currency formatter
Language being used here is Java
Setting up JUnit dependency is easy with Android Studio and Gradle
Your production code is under app/src/main/java/ folder.
Whereas, your test code is under app/src/test/java folder.
Once you create your test class there and write at least 1 test method (will show you in 1 second), Android Studio gives you a nice little green Play icon to run your test.
To mark a method as a test method, simply annate it with @Test
The inputs we use are 0, 1, -1 for example.
Also, we need a big positive and a big negative numbers to test the overflow scenarios.
For each input, we use the assertEquals method from JUnit’s Assert class to check whether our function’s actual outputs matches expected values.
It gives us the confidence that our code works as expected
It’s ok to get failing tests
It’s half of the fun
Say some teammate or yourself dislikes -1 as the output in overflow case and decides to change it to 1 later
Our app will crash or misbehaveWe should instead run our unit tests regularly, every git push for a pull request
We can catch the bug and fix it early
I’m certain you will find some huge functions in your code. Try writing unit test for them, you will see that I mean. Can’t show my code due to confidentiality issue. It wouldn’t make much sense If I censored everything or showed you some dummy code.
Let’s naively do everything in the Activity
A hint here, architecture is the key to Android unit testing here, will expand later
Similar to how we did CalculatorTest, we will create a class CalculatorActivityTest under src/test/java folder
We will naively try to test the updateNumber() method with the help of Mockito
What is Mockito?
Mockito is a popular Java library to assist unit testing
One could always use Robolectric to stub the TextView here
However, it’s slower and may have side effects
As much as they try, Robolectric’s stubs are not the same s Android’s objects
Use Robolectric sparingly
MVP is simplest to start with
There are MVVM, Clean architecture and RIB in the market, check them out when you have time
MVP is the simplest architecture that separate business logics from Activity/ Fragment
We will improve our architecture later
As said, we’ll start with MVP, the simplest architecture ha
This app albeit simple, it fetches data from GitHub API similar to many of your actual apps
This should relates to most of your apps right, communicating with a REST API on your servers or third party servers
Repository class in Data Layer fetches data from GitHub API using Retrofit
searchGitHubRepos calls Repository class to fetch data
Repository class a callback handleSearchGitHubResponse handles the data returned through that callback
Not Robolectric
Let’s write tests
Create a SearchPresenterTest class
First, let’s test searchGitHubRepos method in a happy scenario i.e. a non-null non empty query is passed to it
Switch side is confusing
Reconsider
This time, we run test with coverage
This is how you quantify your work with unit testing
We’ll start today at 0
We’ll soon be at 50
Let’s strive for 80 coverage, you know the 80/20 principle?
It’s important to test the unhappy paths and error handling
Let’s add those tests
Don’t just test the happy path, it’s important to test the edge cases and error cases two
The unhappy scenario here is when search query is null
Here we use Mockito.never() to verify that repository.searchRepos is never called
We’ll also test method handleGitHubReponse’s error handling
Run the tests with coverage again
This time, we 100% test coverage!
To link to next slide
Most variables are reusable, so the 200 lines of setText and setVisibility in my production code will become like 10 lines of code in SearchViewModel