SlideShare uma empresa Scribd logo
1 de 23
Baixar para ler offline
Unit Testing
Using
Mockito in
Android
https://www.bacancytechnology.com/
Introduction
Nowadays mobile applications are getting
complex functionalities & bigger in size, that’s
why writing test cases is very important to
refine code and make sure that each module
works properly (I know it is often
underestimated among the mobile developer
community, sometimes totally ignored!). To
write code that is efficiently unit-testable, we
should use the best suitable architecture like
MVP or MVVM which carries loose coupling
into the Android activities/fragments/adapter.
Three different tests developers should
consider adding in their test suits:


1. UI Tests: These tests are for asserting
application UI. Espresso is used.
2. Instrumented Tests: When we want to verify
user actions like button click etc these tests run
on Android devices, whether physical or
emulated taking the advantage of APIs provided
by the Android framework. AndroidX Test &
Espresso is widely used for the same.
3. Unit Tests: Unit tests are more important for
testing every function and procedure in the
application. For unit testing, mostly used tools
are JUnit, Mockito, or Hamcrest.
The main objective of Unit Testing is to fix bugs
early in the development cycle by verifying the
correctness of code. In this tutorial, we will
learn how what is Mockito and the steps to
implement unit testing using Mockito in
Android application.
Why Mockito?
Often we have classes with dependencies and
methods being dependent on another method
of a different class. When we are unit testing
such methods, we want the unit tests to be
independent of all other dependencies. That’s
why we will Mock the dependency class using
Mockito and test the main class. We can not
achieve this using JUnit.
Hire Android developer from
the award-winning App
Development Company to
stand out in the market and
become the star-solution with
your business idea.


Testing outcomes become
the stories we tell our future
generations of developers at
Bacancy.
Steps: Unit
Testing Using
Mockito in
Android
Let’s take a simple example of computations
like addition, subtraction, etc to understand the
Mockito framework.
We will create a file ComputationActivity.kt to
display all computations upfront. For managing
all operations we will create object class
Operations.kt which will be passed to
ComputationActivity class as a param in the
primary constructor.


class ComputationActivity(private val
operators: Operations) {
fun getAddition(x: Int, y: Int): Int =
operators.add(x, y)
fun getSubtraction(x: Int, y: Int): Int =
operators.subtract(x, y)
fun getMultiplication(x: Int, y: Int): Int =
operators.multiply(x, y)
fun getDivision(x: Int, y: Int): Int =
operators.divide(x, y)
}
Operations.kt class will look like this which will
handle computation functions.


object Operations {
fun add(x: Int, y: Int): Int = x + y
fun subtract(x: Int, y: Int): Int = x - y
fun multiply(x: Int, y: Int): Int = x * y
fun divide(x: Int, y: Int): Int = x / y
}
Add dependencies needed to integrate Mockito
in the build.gradle file.


We will use testImplementation which applies
to the local test source, not the application.
testImplementation 'junit:junit:4.13.2'
testImplementation
'org.mockito:mockito-core:2.25.0'
testImplementation
'org.mockito:mockito-inline:2.13.0'
Folder structure for adding ComputationTest.kt
file for testing ComputationActivity.kt class.


By default, module-name/src/test will be
having source files for local unit tests.
@RunWith – we have annotated with
MockitoJUnitRunner::class which means it
provides the Runner to run the test.
@Mock– Using @Mock annotation we can
mock any class. Mocking any class is
nothing but to create a mock object of a
particular class.
Now, we will add test functions in our
ComputationTest.kt file






Here we will mock the Operations.kt class in
our test file as ComputationActivity.kt file has a
dependency on it.
@RunWith(MockitoJUnitRunner::class)
class ComputationTest {
@Mock
lateinit var operators: Operations
lateinit var computationActivity:
ComputationActivity
}
@Before– Methods annotated with the
@Before annotation are run before each
test. In case you want to run common code
this annotation is very useful. Here we are
initializing ComputationActivity class in
our testing file before running Tests with
the help of @Before annotation.
@Before
fun setUp(){
computationActivity =
ComputationActivity(operators)
}
@Test– To perform the test we need to
annotate the function with @Test.


@Test
fun
givenValidInput_getAddition_shouldCallAddO
perator() {
val x = 5
val y = 10
computationActivity.getAddition(x, y)
verify(operators).add(x, y)
The verify method will check whether ta
particular method of a mock object has been
called or not.
@After– @After annotation is used to run
after each test case completes.
@BeforeClass– @BeforeClass is used when
you want to run a common operation that’s
too expensive to run multiple times. So,
with this annotation, you can execute such
an operation before running all other test.
@AfterClass– Used for deallocation of any
reference after all tests executed
successfully.
Mock marker inline: Mockito can’t test final or
static classes directly. As we know, Kotlin
classes are by default final. So to run tests for
these classes, we need to add marker inline
dependency.


Mockito 2.25.0 had released an important
feature for developers who uses mockito-inline.
To be specific, anyone using Kotlin, which
demands using mockito-inline. Moving towards
our last section of Unit Testing using Mockito in
Android tutorial and run the tests.
Run the Tests
To execute all tests, right-click on
ComputationTest.kt file & select the option
Run


You can even run only one test function by
right-clicking on that function & selecting the
Run option from there.
Github Source:
Unit Testing in
Android
Feel free to visit the source code: mockito-
android-testing and play around with the code!
Conclusion
Mockito is used to test final classes in
Kotlin.
Mockito is a widely used framework for
mobile developers to write unit tests.




So, this was about unit testing using Mockito in
Android application. We have more tutorials
related to mobile development for you! If you
are someone who is looking for Android or iOS
tutorials to start with, then the Mobile
Development tutorials page is for you! Vist the
tutorials and start learning more! You can write
us back if you have any questions or
suggestions! We are happy to help!
Thank you
https://www.bacancytechnology.com/

Mais conteúdo relacionado

Mais procurados

Mais procurados (20)

JUnit & Mockito, first steps
JUnit & Mockito, first stepsJUnit & Mockito, first steps
JUnit & Mockito, first steps
 
Mocking in Java with Mockito
Mocking in Java with MockitoMocking in Java with Mockito
Mocking in Java with Mockito
 
An introduction to unit testing
An introduction to unit testingAn introduction to unit testing
An introduction to unit testing
 
Unit Testing in Angular
Unit Testing in AngularUnit Testing in Angular
Unit Testing in Angular
 
Modern JS with ES6
Modern JS with ES6Modern JS with ES6
Modern JS with ES6
 
Unit Testing
Unit TestingUnit Testing
Unit Testing
 
Selenium-Locators
Selenium-LocatorsSelenium-Locators
Selenium-Locators
 
Unit Test
Unit TestUnit Test
Unit Test
 
Angular Unit Testing
Angular Unit TestingAngular Unit Testing
Angular Unit Testing
 
Junit
JunitJunit
Junit
 
Data abstraction and object orientation
Data abstraction and object orientationData abstraction and object orientation
Data abstraction and object orientation
 
Java interfaces & abstract classes
Java interfaces & abstract classesJava interfaces & abstract classes
Java interfaces & abstract classes
 
Java interface
Java interfaceJava interface
Java interface
 
The New JavaScript: ES6
The New JavaScript: ES6The New JavaScript: ES6
The New JavaScript: ES6
 
Introduction to kotlin and OOP in Kotlin
Introduction to kotlin and OOP in KotlinIntroduction to kotlin and OOP in Kotlin
Introduction to kotlin and OOP in Kotlin
 
Component lifecycle hooks in Angular 2.0
Component lifecycle hooks in Angular 2.0Component lifecycle hooks in Angular 2.0
Component lifecycle hooks in Angular 2.0
 
Unit Testing with Jest
Unit Testing with JestUnit Testing with Jest
Unit Testing with Jest
 
Advanced JavaScript
Advanced JavaScriptAdvanced JavaScript
Advanced JavaScript
 
Vb.net (loop structure)
Vb.net (loop structure)Vb.net (loop structure)
Vb.net (loop structure)
 
JUnit 5
JUnit 5JUnit 5
JUnit 5
 

Semelhante a Unit Testing Using Mockito in Android (1).pdf

Coded ui - lesson 1 - overview
Coded ui - lesson 1 - overviewCoded ui - lesson 1 - overview
Coded ui - lesson 1 - overviewOmer Karpas
 
An Introduction To Unit Testing and TDD
An Introduction To Unit Testing and TDDAn Introduction To Unit Testing and TDD
An Introduction To Unit Testing and TDDAhmed Ehab AbdulAziz
 
Dive into Angular, part 5: Experience
Dive into Angular, part 5: ExperienceDive into Angular, part 5: Experience
Dive into Angular, part 5: ExperienceOleksii Prohonnyi
 
Advanced Dagger talk from 360andev
Advanced Dagger talk from 360andevAdvanced Dagger talk from 360andev
Advanced Dagger talk from 360andevMike Nakhimovich
 
Progressive Mobile Test Automation
Progressive Mobile Test AutomationProgressive Mobile Test Automation
Progressive Mobile Test AutomationRakhi Jain Rohatgi
 
Test automation design patterns
Test automation design patternsTest automation design patterns
Test automation design patternsVitaly Tatarinov
 
Unit Testing Frameworks: A comparative study
Unit Testing Frameworks: A comparative studyUnit Testing Frameworks: A comparative study
Unit Testing Frameworks: A comparative studyIRJET Journal
 
The 2014 Decision Makers Guide to Java Web Frameworks
The 2014 Decision Makers Guide to Java Web FrameworksThe 2014 Decision Makers Guide to Java Web Frameworks
The 2014 Decision Makers Guide to Java Web FrameworksKunal Ashar
 
Fundamental concepts of react js
Fundamental concepts of react jsFundamental concepts of react js
Fundamental concepts of react jsStephieJohn
 
DevOps CI Automation Continuous Integration
DevOps CI Automation Continuous IntegrationDevOps CI Automation Continuous Integration
DevOps CI Automation Continuous IntegrationIRJET Journal
 
Introduction to Integration Tests in Magento / Adobe Commerce
Introduction to Integration Tests in Magento / Adobe CommerceIntroduction to Integration Tests in Magento / Adobe Commerce
Introduction to Integration Tests in Magento / Adobe CommerceBartosz Górski
 
Introduction to Integration Tests in Magento / Adobe Commerce
Introduction to Integration Tests in Magento / Adobe CommerceIntroduction to Integration Tests in Magento / Adobe Commerce
Introduction to Integration Tests in Magento / Adobe CommerceBartosz Górski
 
Utilizando expresso uiautomator na automacao de testes em apps android
Utilizando expresso uiautomator na automacao de testes em apps androidUtilizando expresso uiautomator na automacao de testes em apps android
Utilizando expresso uiautomator na automacao de testes em apps androidtdc-globalcode
 
Embrace Unit Testing
Embrace Unit TestingEmbrace Unit Testing
Embrace Unit Testingalessiopace
 
Visual Automation Framework via Screenshot Comparison
Visual Automation Framework via Screenshot ComparisonVisual Automation Framework via Screenshot Comparison
Visual Automation Framework via Screenshot ComparisonMek Srunyu Stittri
 

Semelhante a Unit Testing Using Mockito in Android (1).pdf (20)

Coded ui - lesson 1 - overview
Coded ui - lesson 1 - overviewCoded ui - lesson 1 - overview
Coded ui - lesson 1 - overview
 
An Introduction To Unit Testing and TDD
An Introduction To Unit Testing and TDDAn Introduction To Unit Testing and TDD
An Introduction To Unit Testing and TDD
 
Coded ui test
Coded ui testCoded ui test
Coded ui test
 
UIAutomator
UIAutomatorUIAutomator
UIAutomator
 
SE2011_10.ppt
SE2011_10.pptSE2011_10.ppt
SE2011_10.ppt
 
Dive into Angular, part 5: Experience
Dive into Angular, part 5: ExperienceDive into Angular, part 5: Experience
Dive into Angular, part 5: Experience
 
Advanced Dagger talk from 360andev
Advanced Dagger talk from 360andevAdvanced Dagger talk from 360andev
Advanced Dagger talk from 360andev
 
Progressive Mobile Test Automation
Progressive Mobile Test AutomationProgressive Mobile Test Automation
Progressive Mobile Test Automation
 
Test automation design patterns
Test automation design patternsTest automation design patterns
Test automation design patterns
 
Unit Testing Frameworks: A comparative study
Unit Testing Frameworks: A comparative studyUnit Testing Frameworks: A comparative study
Unit Testing Frameworks: A comparative study
 
The 2014 Decision Makers Guide to Java Web Frameworks
The 2014 Decision Makers Guide to Java Web FrameworksThe 2014 Decision Makers Guide to Java Web Frameworks
The 2014 Decision Makers Guide to Java Web Frameworks
 
Why test with flex unit
Why test with flex unitWhy test with flex unit
Why test with flex unit
 
Fundamental concepts of react js
Fundamental concepts of react jsFundamental concepts of react js
Fundamental concepts of react js
 
DevOps CI Automation Continuous Integration
DevOps CI Automation Continuous IntegrationDevOps CI Automation Continuous Integration
DevOps CI Automation Continuous Integration
 
Introduction to Integration Tests in Magento / Adobe Commerce
Introduction to Integration Tests in Magento / Adobe CommerceIntroduction to Integration Tests in Magento / Adobe Commerce
Introduction to Integration Tests in Magento / Adobe Commerce
 
Introduction to Integration Tests in Magento / Adobe Commerce
Introduction to Integration Tests in Magento / Adobe CommerceIntroduction to Integration Tests in Magento / Adobe Commerce
Introduction to Integration Tests in Magento / Adobe Commerce
 
Utilizando expresso uiautomator na automacao de testes em apps android
Utilizando expresso uiautomator na automacao de testes em apps androidUtilizando expresso uiautomator na automacao de testes em apps android
Utilizando expresso uiautomator na automacao de testes em apps android
 
Android testing part i
Android testing part iAndroid testing part i
Android testing part i
 
Embrace Unit Testing
Embrace Unit TestingEmbrace Unit Testing
Embrace Unit Testing
 
Visual Automation Framework via Screenshot Comparison
Visual Automation Framework via Screenshot ComparisonVisual Automation Framework via Screenshot Comparison
Visual Automation Framework via Screenshot Comparison
 

Mais de Katy Slemon

Data Science Use Cases in Retail & Healthcare Industries.pdf
Data Science Use Cases in Retail & Healthcare Industries.pdfData Science Use Cases in Retail & Healthcare Industries.pdf
Data Science Use Cases in Retail & Healthcare Industries.pdfKaty Slemon
 
How Much Does It Cost To Hire Golang Developer.pdf
How Much Does It Cost To Hire Golang Developer.pdfHow Much Does It Cost To Hire Golang Developer.pdf
How Much Does It Cost To Hire Golang Developer.pdfKaty Slemon
 
What’s New in Flutter 3.pdf
What’s New in Flutter 3.pdfWhat’s New in Flutter 3.pdf
What’s New in Flutter 3.pdfKaty Slemon
 
How Much Does It Cost To Hire Full Stack Developer In 2022.pdf
How Much Does It Cost To Hire Full Stack Developer In 2022.pdfHow Much Does It Cost To Hire Full Stack Developer In 2022.pdf
How Much Does It Cost To Hire Full Stack Developer In 2022.pdfKaty Slemon
 
How to Implement Middleware Pipeline in VueJS.pdf
How to Implement Middleware Pipeline in VueJS.pdfHow to Implement Middleware Pipeline in VueJS.pdf
How to Implement Middleware Pipeline in VueJS.pdfKaty Slemon
 
How to Build Laravel Package Using Composer.pdf
How to Build Laravel Package Using Composer.pdfHow to Build Laravel Package Using Composer.pdf
How to Build Laravel Package Using Composer.pdfKaty Slemon
 
Sure Shot Ways To Improve And Scale Your Node js Performance.pdf
Sure Shot Ways To Improve And Scale Your Node js Performance.pdfSure Shot Ways To Improve And Scale Your Node js Performance.pdf
Sure Shot Ways To Improve And Scale Your Node js Performance.pdfKaty Slemon
 
How to Develop Slack Bot Using Golang.pdf
How to Develop Slack Bot Using Golang.pdfHow to Develop Slack Bot Using Golang.pdf
How to Develop Slack Bot Using Golang.pdfKaty Slemon
 
IoT Based Battery Management System in Electric Vehicles.pdf
IoT Based Battery Management System in Electric Vehicles.pdfIoT Based Battery Management System in Electric Vehicles.pdf
IoT Based Battery Management System in Electric Vehicles.pdfKaty Slemon
 
Understanding Flexbox Layout in React Native.pdf
Understanding Flexbox Layout in React Native.pdfUnderstanding Flexbox Layout in React Native.pdf
Understanding Flexbox Layout in React Native.pdfKaty Slemon
 
The Ultimate Guide to Laravel Performance Optimization in 2022.pdf
The Ultimate Guide to Laravel Performance Optimization in 2022.pdfThe Ultimate Guide to Laravel Performance Optimization in 2022.pdf
The Ultimate Guide to Laravel Performance Optimization in 2022.pdfKaty Slemon
 
New Features in iOS 15 and Swift 5.5.pdf
New Features in iOS 15 and Swift 5.5.pdfNew Features in iOS 15 and Swift 5.5.pdf
New Features in iOS 15 and Swift 5.5.pdfKaty Slemon
 
Choose the Right Battery Management System for Lithium Ion Batteries.pdf
Choose the Right Battery Management System for Lithium Ion Batteries.pdfChoose the Right Battery Management System for Lithium Ion Batteries.pdf
Choose the Right Battery Management System for Lithium Ion Batteries.pdfKaty Slemon
 
Angular Universal How to Build Angular SEO Friendly App.pdf
Angular Universal How to Build Angular SEO Friendly App.pdfAngular Universal How to Build Angular SEO Friendly App.pdf
Angular Universal How to Build Angular SEO Friendly App.pdfKaty Slemon
 
Ruby On Rails Performance Tuning Guide.pdf
Ruby On Rails Performance Tuning Guide.pdfRuby On Rails Performance Tuning Guide.pdf
Ruby On Rails Performance Tuning Guide.pdfKaty Slemon
 
Uncovering 04 Main Types and Benefits of Salesforce ISV Partnerships.pdf
Uncovering 04 Main Types and Benefits of Salesforce ISV Partnerships.pdfUncovering 04 Main Types and Benefits of Salesforce ISV Partnerships.pdf
Uncovering 04 Main Types and Benefits of Salesforce ISV Partnerships.pdfKaty Slemon
 
Why Use React Js A Complete Guide (1).pdf
Why Use React Js A Complete Guide (1).pdfWhy Use React Js A Complete Guide (1).pdf
Why Use React Js A Complete Guide (1).pdfKaty Slemon
 
Why Use Ruby on Rails for eCommerce Project Proven Case Study.pdf
Why Use Ruby on Rails for eCommerce Project Proven Case Study.pdfWhy Use Ruby on Rails for eCommerce Project Proven Case Study.pdf
Why Use Ruby on Rails for eCommerce Project Proven Case Study.pdfKaty Slemon
 
Bacancy’s CCS2CON is Now Charging Compliant with Top Indian EVs.pdf
Bacancy’s CCS2CON is Now Charging Compliant with Top Indian EVs.pdfBacancy’s CCS2CON is Now Charging Compliant with Top Indian EVs.pdf
Bacancy’s CCS2CON is Now Charging Compliant with Top Indian EVs.pdfKaty Slemon
 
How to Integrate Google Adwords API in Laravel App.pdf
How to Integrate Google Adwords API in Laravel App.pdfHow to Integrate Google Adwords API in Laravel App.pdf
How to Integrate Google Adwords API in Laravel App.pdfKaty Slemon
 

Mais de Katy Slemon (20)

Data Science Use Cases in Retail & Healthcare Industries.pdf
Data Science Use Cases in Retail & Healthcare Industries.pdfData Science Use Cases in Retail & Healthcare Industries.pdf
Data Science Use Cases in Retail & Healthcare Industries.pdf
 
How Much Does It Cost To Hire Golang Developer.pdf
How Much Does It Cost To Hire Golang Developer.pdfHow Much Does It Cost To Hire Golang Developer.pdf
How Much Does It Cost To Hire Golang Developer.pdf
 
What’s New in Flutter 3.pdf
What’s New in Flutter 3.pdfWhat’s New in Flutter 3.pdf
What’s New in Flutter 3.pdf
 
How Much Does It Cost To Hire Full Stack Developer In 2022.pdf
How Much Does It Cost To Hire Full Stack Developer In 2022.pdfHow Much Does It Cost To Hire Full Stack Developer In 2022.pdf
How Much Does It Cost To Hire Full Stack Developer In 2022.pdf
 
How to Implement Middleware Pipeline in VueJS.pdf
How to Implement Middleware Pipeline in VueJS.pdfHow to Implement Middleware Pipeline in VueJS.pdf
How to Implement Middleware Pipeline in VueJS.pdf
 
How to Build Laravel Package Using Composer.pdf
How to Build Laravel Package Using Composer.pdfHow to Build Laravel Package Using Composer.pdf
How to Build Laravel Package Using Composer.pdf
 
Sure Shot Ways To Improve And Scale Your Node js Performance.pdf
Sure Shot Ways To Improve And Scale Your Node js Performance.pdfSure Shot Ways To Improve And Scale Your Node js Performance.pdf
Sure Shot Ways To Improve And Scale Your Node js Performance.pdf
 
How to Develop Slack Bot Using Golang.pdf
How to Develop Slack Bot Using Golang.pdfHow to Develop Slack Bot Using Golang.pdf
How to Develop Slack Bot Using Golang.pdf
 
IoT Based Battery Management System in Electric Vehicles.pdf
IoT Based Battery Management System in Electric Vehicles.pdfIoT Based Battery Management System in Electric Vehicles.pdf
IoT Based Battery Management System in Electric Vehicles.pdf
 
Understanding Flexbox Layout in React Native.pdf
Understanding Flexbox Layout in React Native.pdfUnderstanding Flexbox Layout in React Native.pdf
Understanding Flexbox Layout in React Native.pdf
 
The Ultimate Guide to Laravel Performance Optimization in 2022.pdf
The Ultimate Guide to Laravel Performance Optimization in 2022.pdfThe Ultimate Guide to Laravel Performance Optimization in 2022.pdf
The Ultimate Guide to Laravel Performance Optimization in 2022.pdf
 
New Features in iOS 15 and Swift 5.5.pdf
New Features in iOS 15 and Swift 5.5.pdfNew Features in iOS 15 and Swift 5.5.pdf
New Features in iOS 15 and Swift 5.5.pdf
 
Choose the Right Battery Management System for Lithium Ion Batteries.pdf
Choose the Right Battery Management System for Lithium Ion Batteries.pdfChoose the Right Battery Management System for Lithium Ion Batteries.pdf
Choose the Right Battery Management System for Lithium Ion Batteries.pdf
 
Angular Universal How to Build Angular SEO Friendly App.pdf
Angular Universal How to Build Angular SEO Friendly App.pdfAngular Universal How to Build Angular SEO Friendly App.pdf
Angular Universal How to Build Angular SEO Friendly App.pdf
 
Ruby On Rails Performance Tuning Guide.pdf
Ruby On Rails Performance Tuning Guide.pdfRuby On Rails Performance Tuning Guide.pdf
Ruby On Rails Performance Tuning Guide.pdf
 
Uncovering 04 Main Types and Benefits of Salesforce ISV Partnerships.pdf
Uncovering 04 Main Types and Benefits of Salesforce ISV Partnerships.pdfUncovering 04 Main Types and Benefits of Salesforce ISV Partnerships.pdf
Uncovering 04 Main Types and Benefits of Salesforce ISV Partnerships.pdf
 
Why Use React Js A Complete Guide (1).pdf
Why Use React Js A Complete Guide (1).pdfWhy Use React Js A Complete Guide (1).pdf
Why Use React Js A Complete Guide (1).pdf
 
Why Use Ruby on Rails for eCommerce Project Proven Case Study.pdf
Why Use Ruby on Rails for eCommerce Project Proven Case Study.pdfWhy Use Ruby on Rails for eCommerce Project Proven Case Study.pdf
Why Use Ruby on Rails for eCommerce Project Proven Case Study.pdf
 
Bacancy’s CCS2CON is Now Charging Compliant with Top Indian EVs.pdf
Bacancy’s CCS2CON is Now Charging Compliant with Top Indian EVs.pdfBacancy’s CCS2CON is Now Charging Compliant with Top Indian EVs.pdf
Bacancy’s CCS2CON is Now Charging Compliant with Top Indian EVs.pdf
 
How to Integrate Google Adwords API in Laravel App.pdf
How to Integrate Google Adwords API in Laravel App.pdfHow to Integrate Google Adwords API in Laravel App.pdf
How to Integrate Google Adwords API in Laravel App.pdf
 

Último

3 Pitfalls Everyone Should Avoid with Cloud Data
3 Pitfalls Everyone Should Avoid with Cloud Data3 Pitfalls Everyone Should Avoid with Cloud Data
3 Pitfalls Everyone Should Avoid with Cloud DataEric D. Schabell
 
Webinar: The Art of Prioritizing Your Product Roadmap by AWS Sr PM - Tech
Webinar: The Art of Prioritizing Your Product Roadmap by AWS Sr PM - TechWebinar: The Art of Prioritizing Your Product Roadmap by AWS Sr PM - Tech
Webinar: The Art of Prioritizing Your Product Roadmap by AWS Sr PM - TechProduct School
 
Planetek Italia Srl - Corporate Profile Brochure
Planetek Italia Srl - Corporate Profile BrochurePlanetek Italia Srl - Corporate Profile Brochure
Planetek Italia Srl - Corporate Profile BrochurePlanetek Italia Srl
 
The Zero-ETL Approach: Enhancing Data Agility and Insight
The Zero-ETL Approach: Enhancing Data Agility and InsightThe Zero-ETL Approach: Enhancing Data Agility and Insight
The Zero-ETL Approach: Enhancing Data Agility and InsightSafe Software
 
Novo Nordisk's journey in developing an open-source application on Neo4j
Novo Nordisk's journey in developing an open-source application on Neo4jNovo Nordisk's journey in developing an open-source application on Neo4j
Novo Nordisk's journey in developing an open-source application on Neo4jNeo4j
 
Technical SEO for Improved Accessibility WTS FEST
Technical SEO for Improved Accessibility  WTS FESTTechnical SEO for Improved Accessibility  WTS FEST
Technical SEO for Improved Accessibility WTS FESTBillieHyde
 
How to release an Open Source Dataweave Library
How to release an Open Source Dataweave LibraryHow to release an Open Source Dataweave Library
How to release an Open Source Dataweave Libraryshyamraj55
 
March Patch Tuesday
March Patch TuesdayMarch Patch Tuesday
March Patch TuesdayIvanti
 
From the origin to the future of Open Source model and business
From the origin to the future of  Open Source model and businessFrom the origin to the future of  Open Source model and business
From the origin to the future of Open Source model and businessFrancesco Corti
 
Introduction to RAG (Retrieval Augmented Generation) and its application
Introduction to RAG (Retrieval Augmented Generation) and its applicationIntroduction to RAG (Retrieval Augmented Generation) and its application
Introduction to RAG (Retrieval Augmented Generation) and its applicationKnoldus Inc.
 
2024.03.12 Cost drivers of cultivated meat production.pdf
2024.03.12 Cost drivers of cultivated meat production.pdf2024.03.12 Cost drivers of cultivated meat production.pdf
2024.03.12 Cost drivers of cultivated meat production.pdfThe Good Food Institute
 
TrustArc Webinar - How to Live in a Post Third-Party Cookie World
TrustArc Webinar - How to Live in a Post Third-Party Cookie WorldTrustArc Webinar - How to Live in a Post Third-Party Cookie World
TrustArc Webinar - How to Live in a Post Third-Party Cookie WorldTrustArc
 
Automation Ops Series: Session 2 - Governance for UiPath projects
Automation Ops Series: Session 2 - Governance for UiPath projectsAutomation Ops Series: Session 2 - Governance for UiPath projects
Automation Ops Series: Session 2 - Governance for UiPath projectsDianaGray10
 
Explore the UiPath Community and ways you can benefit on your journey to auto...
Explore the UiPath Community and ways you can benefit on your journey to auto...Explore the UiPath Community and ways you can benefit on your journey to auto...
Explore the UiPath Community and ways you can benefit on your journey to auto...DianaGray10
 
Patch notes explaining DISARM Version 1.4 update
Patch notes explaining DISARM Version 1.4 updatePatch notes explaining DISARM Version 1.4 update
Patch notes explaining DISARM Version 1.4 updateadam112203
 
SIM INFORMATION SYSTEM: REVOLUTIONIZING DATA MANAGEMENT
SIM INFORMATION SYSTEM: REVOLUTIONIZING DATA MANAGEMENTSIM INFORMATION SYSTEM: REVOLUTIONIZING DATA MANAGEMENT
SIM INFORMATION SYSTEM: REVOLUTIONIZING DATA MANAGEMENTxtailishbaloch
 
My key hands-on projects in Quantum, and QAI
My key hands-on projects in Quantum, and QAIMy key hands-on projects in Quantum, and QAI
My key hands-on projects in Quantum, and QAIVijayananda Mohire
 
UiPath Studio Web workshop series - Day 2
UiPath Studio Web workshop series - Day 2UiPath Studio Web workshop series - Day 2
UiPath Studio Web workshop series - Day 2DianaGray10
 
Flow Control | Block Size | ST Min | First Frame
Flow Control | Block Size | ST Min | First FrameFlow Control | Block Size | ST Min | First Frame
Flow Control | Block Size | ST Min | First FrameKapil Thakar
 

Último (20)

3 Pitfalls Everyone Should Avoid with Cloud Data
3 Pitfalls Everyone Should Avoid with Cloud Data3 Pitfalls Everyone Should Avoid with Cloud Data
3 Pitfalls Everyone Should Avoid with Cloud Data
 
Webinar: The Art of Prioritizing Your Product Roadmap by AWS Sr PM - Tech
Webinar: The Art of Prioritizing Your Product Roadmap by AWS Sr PM - TechWebinar: The Art of Prioritizing Your Product Roadmap by AWS Sr PM - Tech
Webinar: The Art of Prioritizing Your Product Roadmap by AWS Sr PM - Tech
 
Planetek Italia Srl - Corporate Profile Brochure
Planetek Italia Srl - Corporate Profile BrochurePlanetek Italia Srl - Corporate Profile Brochure
Planetek Italia Srl - Corporate Profile Brochure
 
The Zero-ETL Approach: Enhancing Data Agility and Insight
The Zero-ETL Approach: Enhancing Data Agility and InsightThe Zero-ETL Approach: Enhancing Data Agility and Insight
The Zero-ETL Approach: Enhancing Data Agility and Insight
 
Novo Nordisk's journey in developing an open-source application on Neo4j
Novo Nordisk's journey in developing an open-source application on Neo4jNovo Nordisk's journey in developing an open-source application on Neo4j
Novo Nordisk's journey in developing an open-source application on Neo4j
 
Technical SEO for Improved Accessibility WTS FEST
Technical SEO for Improved Accessibility  WTS FESTTechnical SEO for Improved Accessibility  WTS FEST
Technical SEO for Improved Accessibility WTS FEST
 
How to release an Open Source Dataweave Library
How to release an Open Source Dataweave LibraryHow to release an Open Source Dataweave Library
How to release an Open Source Dataweave Library
 
SheDev 2024
SheDev 2024SheDev 2024
SheDev 2024
 
March Patch Tuesday
March Patch TuesdayMarch Patch Tuesday
March Patch Tuesday
 
From the origin to the future of Open Source model and business
From the origin to the future of  Open Source model and businessFrom the origin to the future of  Open Source model and business
From the origin to the future of Open Source model and business
 
Introduction to RAG (Retrieval Augmented Generation) and its application
Introduction to RAG (Retrieval Augmented Generation) and its applicationIntroduction to RAG (Retrieval Augmented Generation) and its application
Introduction to RAG (Retrieval Augmented Generation) and its application
 
2024.03.12 Cost drivers of cultivated meat production.pdf
2024.03.12 Cost drivers of cultivated meat production.pdf2024.03.12 Cost drivers of cultivated meat production.pdf
2024.03.12 Cost drivers of cultivated meat production.pdf
 
TrustArc Webinar - How to Live in a Post Third-Party Cookie World
TrustArc Webinar - How to Live in a Post Third-Party Cookie WorldTrustArc Webinar - How to Live in a Post Third-Party Cookie World
TrustArc Webinar - How to Live in a Post Third-Party Cookie World
 
Automation Ops Series: Session 2 - Governance for UiPath projects
Automation Ops Series: Session 2 - Governance for UiPath projectsAutomation Ops Series: Session 2 - Governance for UiPath projects
Automation Ops Series: Session 2 - Governance for UiPath projects
 
Explore the UiPath Community and ways you can benefit on your journey to auto...
Explore the UiPath Community and ways you can benefit on your journey to auto...Explore the UiPath Community and ways you can benefit on your journey to auto...
Explore the UiPath Community and ways you can benefit on your journey to auto...
 
Patch notes explaining DISARM Version 1.4 update
Patch notes explaining DISARM Version 1.4 updatePatch notes explaining DISARM Version 1.4 update
Patch notes explaining DISARM Version 1.4 update
 
SIM INFORMATION SYSTEM: REVOLUTIONIZING DATA MANAGEMENT
SIM INFORMATION SYSTEM: REVOLUTIONIZING DATA MANAGEMENTSIM INFORMATION SYSTEM: REVOLUTIONIZING DATA MANAGEMENT
SIM INFORMATION SYSTEM: REVOLUTIONIZING DATA MANAGEMENT
 
My key hands-on projects in Quantum, and QAI
My key hands-on projects in Quantum, and QAIMy key hands-on projects in Quantum, and QAI
My key hands-on projects in Quantum, and QAI
 
UiPath Studio Web workshop series - Day 2
UiPath Studio Web workshop series - Day 2UiPath Studio Web workshop series - Day 2
UiPath Studio Web workshop series - Day 2
 
Flow Control | Block Size | ST Min | First Frame
Flow Control | Block Size | ST Min | First FrameFlow Control | Block Size | ST Min | First Frame
Flow Control | Block Size | ST Min | First Frame
 

Unit Testing Using Mockito in Android (1).pdf

  • 3. Nowadays mobile applications are getting complex functionalities & bigger in size, that’s why writing test cases is very important to refine code and make sure that each module works properly (I know it is often underestimated among the mobile developer community, sometimes totally ignored!). To write code that is efficiently unit-testable, we should use the best suitable architecture like MVP or MVVM which carries loose coupling into the Android activities/fragments/adapter.
  • 4. Three different tests developers should consider adding in their test suits: 1. UI Tests: These tests are for asserting application UI. Espresso is used. 2. Instrumented Tests: When we want to verify user actions like button click etc these tests run on Android devices, whether physical or emulated taking the advantage of APIs provided by the Android framework. AndroidX Test & Espresso is widely used for the same. 3. Unit Tests: Unit tests are more important for testing every function and procedure in the application. For unit testing, mostly used tools are JUnit, Mockito, or Hamcrest. The main objective of Unit Testing is to fix bugs early in the development cycle by verifying the correctness of code. In this tutorial, we will learn how what is Mockito and the steps to implement unit testing using Mockito in Android application.
  • 6. Often we have classes with dependencies and methods being dependent on another method of a different class. When we are unit testing such methods, we want the unit tests to be independent of all other dependencies. That’s why we will Mock the dependency class using Mockito and test the main class. We can not achieve this using JUnit.
  • 7. Hire Android developer from the award-winning App Development Company to stand out in the market and become the star-solution with your business idea. Testing outcomes become the stories we tell our future generations of developers at Bacancy.
  • 9. Let’s take a simple example of computations like addition, subtraction, etc to understand the Mockito framework. We will create a file ComputationActivity.kt to display all computations upfront. For managing all operations we will create object class Operations.kt which will be passed to ComputationActivity class as a param in the primary constructor. class ComputationActivity(private val operators: Operations) { fun getAddition(x: Int, y: Int): Int = operators.add(x, y) fun getSubtraction(x: Int, y: Int): Int = operators.subtract(x, y) fun getMultiplication(x: Int, y: Int): Int = operators.multiply(x, y) fun getDivision(x: Int, y: Int): Int = operators.divide(x, y) }
  • 10. Operations.kt class will look like this which will handle computation functions. object Operations { fun add(x: Int, y: Int): Int = x + y fun subtract(x: Int, y: Int): Int = x - y fun multiply(x: Int, y: Int): Int = x * y fun divide(x: Int, y: Int): Int = x / y } Add dependencies needed to integrate Mockito in the build.gradle file. We will use testImplementation which applies to the local test source, not the application.
  • 11. testImplementation 'junit:junit:4.13.2' testImplementation 'org.mockito:mockito-core:2.25.0' testImplementation 'org.mockito:mockito-inline:2.13.0' Folder structure for adding ComputationTest.kt file for testing ComputationActivity.kt class. By default, module-name/src/test will be having source files for local unit tests.
  • 12. @RunWith – we have annotated with MockitoJUnitRunner::class which means it provides the Runner to run the test. @Mock– Using @Mock annotation we can mock any class. Mocking any class is nothing but to create a mock object of a particular class. Now, we will add test functions in our ComputationTest.kt file Here we will mock the Operations.kt class in our test file as ComputationActivity.kt file has a dependency on it.
  • 13. @RunWith(MockitoJUnitRunner::class) class ComputationTest { @Mock lateinit var operators: Operations lateinit var computationActivity: ComputationActivity } @Before– Methods annotated with the @Before annotation are run before each test. In case you want to run common code this annotation is very useful. Here we are initializing ComputationActivity class in our testing file before running Tests with the help of @Before annotation.
  • 14. @Before fun setUp(){ computationActivity = ComputationActivity(operators) } @Test– To perform the test we need to annotate the function with @Test. @Test fun givenValidInput_getAddition_shouldCallAddO perator() { val x = 5 val y = 10 computationActivity.getAddition(x, y) verify(operators).add(x, y)
  • 15. The verify method will check whether ta particular method of a mock object has been called or not. @After– @After annotation is used to run after each test case completes. @BeforeClass– @BeforeClass is used when you want to run a common operation that’s too expensive to run multiple times. So, with this annotation, you can execute such an operation before running all other test. @AfterClass– Used for deallocation of any reference after all tests executed successfully.
  • 16. Mock marker inline: Mockito can’t test final or static classes directly. As we know, Kotlin classes are by default final. So to run tests for these classes, we need to add marker inline dependency. Mockito 2.25.0 had released an important feature for developers who uses mockito-inline. To be specific, anyone using Kotlin, which demands using mockito-inline. Moving towards our last section of Unit Testing using Mockito in Android tutorial and run the tests.
  • 18. To execute all tests, right-click on ComputationTest.kt file & select the option Run You can even run only one test function by right-clicking on that function & selecting the Run option from there.
  • 20. Feel free to visit the source code: mockito- android-testing and play around with the code!
  • 22. Mockito is used to test final classes in Kotlin. Mockito is a widely used framework for mobile developers to write unit tests. So, this was about unit testing using Mockito in Android application. We have more tutorials related to mobile development for you! If you are someone who is looking for Android or iOS tutorials to start with, then the Mobile Development tutorials page is for you! Vist the tutorials and start learning more! You can write us back if you have any questions or suggestions! We are happy to help!