A Complete Guide On Unit Testing Using Mockito In Android

Page 1

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.


Testing outcomes become the stories we tell our future generations of developers at Bacancy. 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.


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.


Now, we will add test functions in our ComputationTest.kt file @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. 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: mockitoandroid-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/


Turn static files into dynamic content formats.

Create a flipbook
Issuu converts static files into: digital portfolios, online yearbooks, online catalogs, digital photo albums and more. Sign up and create your flipbook.