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

Unit Testing And Mocking
Unit Testing And MockingUnit Testing And Mocking
Unit Testing And Mocking
Joe Wilson
 

What's hot (20)

JUnit Presentation
JUnit PresentationJUnit Presentation
JUnit Presentation
 
Builder Design Pattern (Generic Construction -Different Representation)
Builder Design Pattern (Generic Construction -Different Representation)Builder Design Pattern (Generic Construction -Different Representation)
Builder Design Pattern (Generic Construction -Different Representation)
 
Unit Testing Android Applications
Unit Testing Android ApplicationsUnit Testing Android Applications
Unit Testing Android Applications
 
Jetpack Navigation Component
Jetpack Navigation ComponentJetpack Navigation Component
Jetpack Navigation Component
 
Writing and using Hamcrest Matchers
Writing and using Hamcrest MatchersWriting and using Hamcrest Matchers
Writing and using Hamcrest Matchers
 
JUNit Presentation
JUNit PresentationJUNit Presentation
JUNit Presentation
 
Git
GitGit
Git
 
Gradle Introduction
Gradle IntroductionGradle Introduction
Gradle Introduction
 
Php Tutorial
Php TutorialPhp Tutorial
Php Tutorial
 
Junit
JunitJunit
Junit
 
Git and Github
Git and GithubGit and Github
Git and Github
 
Unit Testing And Mocking
Unit Testing And MockingUnit Testing And Mocking
Unit Testing And Mocking
 
Git tutorial
Git tutorialGit tutorial
Git tutorial
 
Unit testing with JUnit
Unit testing with JUnitUnit testing with JUnit
Unit testing with JUnit
 
Intro to git and git hub
Intro to git and git hubIntro to git and git hub
Intro to git and git hub
 
Groovy intro
Groovy introGroovy intro
Groovy intro
 
AngularJS Architecture
AngularJS ArchitectureAngularJS Architecture
AngularJS Architecture
 
Git Lab Introduction
Git Lab IntroductionGit Lab Introduction
Git Lab Introduction
 
Android JetPack: easy navigation with the new Navigation Controller
Android JetPack: easy navigation with the new Navigation ControllerAndroid JetPack: easy navigation with the new Navigation Controller
Android JetPack: easy navigation with the new Navigation Controller
 
Version Control with Git
Version Control with GitVersion Control with Git
Version Control with Git
 

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

Progressive Mobile Test Automation
Progressive Mobile Test AutomationProgressive Mobile Test Automation
Progressive Mobile Test Automation
Rakhi Jain Rohatgi
 

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

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

Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Victor Rentea
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Victor Rentea
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 

Recently uploaded (20)

Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
Web Form Automation for Bonterra Impact Management (fka Social Solutions Apri...
 
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
 
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemkeProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
ProductAnonymous-April2024-WinProductDiscovery-MelissaKlemke
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024Finding Java's Hidden Performance Traps @ DevoxxUK 2024
Finding Java's Hidden Performance Traps @ DevoxxUK 2024
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
 
DBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor PresentationDBX First Quarter 2024 Investor Presentation
DBX First Quarter 2024 Investor Presentation
 
FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024FWD Group - Insurer Innovation Award 2024
FWD Group - Insurer Innovation Award 2024
 
Vector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptxVector Search -An Introduction in Oracle Database 23ai.pptx
Vector Search -An Introduction in Oracle Database 23ai.pptx
 
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ..."I see eyes in my soup": How Delivery Hero implemented the safety system for ...
"I see eyes in my soup": How Delivery Hero implemented the safety system for ...
 
Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)Introduction to Multilingual Retrieval Augmented Generation (RAG)
Introduction to Multilingual Retrieval Augmented Generation (RAG)
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
 
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
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
WSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering DevelopersWSO2's API Vision: Unifying Control, Empowering Developers
WSO2's API Vision: Unifying Control, Empowering Developers
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
Six Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal OntologySix Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal Ontology
 
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 AmsterdamDEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
DEV meet-up UiPath Document Understanding May 7 2024 Amsterdam
 

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!