SlideShare a Scribd company logo
1 of 23
Download to read 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/

More Related Content

What's hot

Jetpack Compose beginner.pdf
Jetpack Compose beginner.pdfJetpack Compose beginner.pdf
Jetpack Compose beginner.pdfAayushmaAgrawal
 
Introduction to React JS
Introduction to React JSIntroduction to React JS
Introduction to React JSArno Lordkronos
 
Introduction to Koltin for Android Part I
Introduction to Koltin for Android Part I Introduction to Koltin for Android Part I
Introduction to Koltin for Android Part I Atif AbbAsi
 
Android Development with Kotlin, Part 1 - Introduction
Android Development with Kotlin, Part 1 - IntroductionAndroid Development with Kotlin, Part 1 - Introduction
Android Development with Kotlin, Part 1 - IntroductionAndreas Jakl
 
TypeScript Introduction
TypeScript IntroductionTypeScript Introduction
TypeScript IntroductionDmitry Sheiko
 
Introducing type script
Introducing type scriptIntroducing type script
Introducing type scriptRemo Jansen
 
Understanding react hooks
Understanding react hooksUnderstanding react hooks
Understanding react hooksMaulik Shah
 
React Context API
React Context APIReact Context API
React Context APINodeXperts
 

What's hot (20)

Jetpack Compose beginner.pdf
Jetpack Compose beginner.pdfJetpack Compose beginner.pdf
Jetpack Compose beginner.pdf
 
testng
testngtestng
testng
 
Builder pattern
Builder patternBuilder pattern
Builder pattern
 
Introduction to React JS
Introduction to React JSIntroduction to React JS
Introduction to React JS
 
Introduction to Koltin for Android Part I
Introduction to Koltin for Android Part I Introduction to Koltin for Android Part I
Introduction to Koltin for Android Part I
 
Typescript ppt
Typescript pptTypescript ppt
Typescript ppt
 
WEB DEVELOPMENT USING REACT JS
 WEB DEVELOPMENT USING REACT JS WEB DEVELOPMENT USING REACT JS
WEB DEVELOPMENT USING REACT JS
 
SQLite database in android
SQLite database in androidSQLite database in android
SQLite database in android
 
Android Development with Kotlin, Part 1 - Introduction
Android Development with Kotlin, Part 1 - IntroductionAndroid Development with Kotlin, Part 1 - Introduction
Android Development with Kotlin, Part 1 - Introduction
 
TypeScript Introduction
TypeScript IntroductionTypeScript Introduction
TypeScript Introduction
 
Ios development
Ios developmentIos development
Ios development
 
ReactJS presentation.pptx
ReactJS presentation.pptxReactJS presentation.pptx
ReactJS presentation.pptx
 
Learning typescript
Learning typescriptLearning typescript
Learning typescript
 
Jenkins tutorial
Jenkins tutorialJenkins tutorial
Jenkins tutorial
 
Introducing type script
Introducing type scriptIntroducing type script
Introducing type script
 
Introduction to spring boot
Introduction to spring bootIntroduction to spring boot
Introduction to spring boot
 
Javascript essentials
Javascript essentialsJavascript essentials
Javascript essentials
 
React Native Workshop
React Native WorkshopReact Native Workshop
React Native Workshop
 
Understanding react hooks
Understanding react hooksUnderstanding react hooks
Understanding react hooks
 
React Context API
React Context APIReact Context API
React Context API
 

Similar to Unit Testing Using Mockito in Android (1).pdf

Unit Testing in Flutter - From Workflow Essentials to Complex Scenarios
Unit Testing in Flutter - From Workflow Essentials to Complex ScenariosUnit Testing in Flutter - From Workflow Essentials to Complex Scenarios
Unit Testing in Flutter - From Workflow Essentials to Complex ScenariosFlutter Agency
 
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
 

Similar to Unit Testing Using Mockito in Android (1).pdf (20)

Unit Testing in Flutter - From Workflow Essentials to Complex Scenarios
Unit Testing in Flutter - From Workflow Essentials to Complex ScenariosUnit Testing in Flutter - From Workflow Essentials to Complex Scenarios
Unit Testing in Flutter - From Workflow Essentials to Complex Scenarios
 
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
 

More from Katy Slemon

React Alternatives Frameworks- Lightweight Javascript Libraries.pdf
React Alternatives Frameworks- Lightweight Javascript Libraries.pdfReact Alternatives Frameworks- Lightweight Javascript Libraries.pdf
React Alternatives Frameworks- Lightweight Javascript Libraries.pdfKaty 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
 
Why Use Ruby On Rails.pdf
Why Use Ruby On Rails.pdfWhy Use Ruby On Rails.pdf
Why Use Ruby On Rails.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
 
How to Hire & Manage Dedicated Team For Your Next Product Development.pdf
How to Hire & Manage Dedicated Team For Your Next Product Development.pdfHow to Hire & Manage Dedicated Team For Your Next Product Development.pdf
How to Hire & Manage Dedicated Team For Your Next Product Development.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
 
Flutter Performance Tuning Best Practices From the Pros.pdf
Flutter Performance Tuning Best Practices From the Pros.pdfFlutter Performance Tuning Best Practices From the Pros.pdf
Flutter Performance Tuning Best Practices From the Pros.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
 
How to Set Up and Send Mails Using SendGrid in NodeJs App.pdf
How to Set Up and Send Mails Using SendGrid in NodeJs App.pdfHow to Set Up and Send Mails Using SendGrid in NodeJs App.pdf
How to Set Up and Send Mails Using SendGrid in NodeJs 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
 

More from Katy Slemon (20)

React Alternatives Frameworks- Lightweight Javascript Libraries.pdf
React Alternatives Frameworks- Lightweight Javascript Libraries.pdfReact Alternatives Frameworks- Lightweight Javascript Libraries.pdf
React Alternatives Frameworks- Lightweight Javascript Libraries.pdf
 
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
 
Why Use Ruby On Rails.pdf
Why Use Ruby On Rails.pdfWhy Use Ruby On Rails.pdf
Why Use Ruby On Rails.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
 
How to Hire & Manage Dedicated Team For Your Next Product Development.pdf
How to Hire & Manage Dedicated Team For Your Next Product Development.pdfHow to Hire & Manage Dedicated Team For Your Next Product Development.pdf
How to Hire & Manage Dedicated Team For Your Next Product Development.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
 
Flutter Performance Tuning Best Practices From the Pros.pdf
Flutter Performance Tuning Best Practices From the Pros.pdfFlutter Performance Tuning Best Practices From the Pros.pdf
Flutter Performance Tuning Best Practices From the Pros.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
 
How to Set Up and Send Mails Using SendGrid in NodeJs App.pdf
How to Set Up and Send Mails Using SendGrid in NodeJs App.pdfHow to Set Up and Send Mails Using SendGrid in NodeJs App.pdf
How to Set Up and Send Mails Using SendGrid in NodeJs 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
 

Recently uploaded

HTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesHTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesBoston Institute of Analytics
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodJuan lago vázquez
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)wesley chun
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...apidays
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?Igalia
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024The Digital Insurer
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyKhushali Kathiriya
 
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...Principled Technologies
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAndrey Devyatkin
 
Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024SynarionITSolutions
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUK Journal
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...apidays
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 

Recently uploaded (20)

HTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation StrategiesHTML Injection Attacks: Impact and Mitigation Strategies
HTML Injection Attacks: Impact and Mitigation Strategies
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024Top 10 Most Downloaded Games on Play Store in 2024
Top 10 Most Downloaded Games on Play Store in 2024
 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
 
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
Apidays New York 2024 - The Good, the Bad and the Governed by David O'Neill, ...
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 

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!