{"id":25112,"date":"2022-03-25T10:49:51","date_gmt":"2022-03-25T10:49:51","guid":{"rendered":"https:\/\/www.bacancytechnology.com\/blog\/?p=25112"},"modified":"2024-06-04T08:31:14","modified_gmt":"2024-06-04T08:31:14","slug":"unit-testing-using-mockito-in-android","status":"publish","type":"post","link":"https:\/\/www.bacancytechnology.com\/blog\/unit-testing-using-mockito-in-android","title":{"rendered":"Unit Testing Using Mockito in Android"},"content":{"rendered":"<h2>Introduction<\/h2>\n<p>Nowadays mobile applications are getting complex functionalities &#038; bigger in size, that\u2019s 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.<\/p>\n<p>Three different tests developers should consider adding in their test suits:<br \/>\n<strong>1. UI Tests:<\/strong> These tests are for asserting application UI. Espresso is used.<\/p>\n<p><strong>2. Instrumented Tests:<\/strong> 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 &#038; Espresso is widely used for the same.<\/p>\n<p><strong>3. Unit Tests:<\/strong> 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.<\/p>\n<p>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. <\/p>\n<h2>Why Mockito?<\/h2>\n<p>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\u2019s why we will Mock the dependency class using Mockito and test the main class. We can not achieve this using JUnit.<\/p>\n<p class=\"boxed bg--secondary\" style=\"border: 1px solid #c7c7c7; box-shadow: 0 0 40px rgba(0, 0, 0, 0.2);\"><strong><i><span style=\"font-size:22px; color:#000;\">Testing outcomes become the stories we tell our future generations of developers at Bacancy.<\/span><br \/>\n<a href=\"https:\/\/www.bacancytechnology.com\/android-application-development\" target=\"_blank\" rel=\"noopener\">Hire Android developer<\/a> from the award-winning App Development Company to stand out in the market and become the star-solution with your business idea.<\/i><\/strong><\/p>\n<p>Now moving towards our demo application. <\/p>\n<h2>Steps: Unit Testing using Mockito in Android<\/h2>\n<p>Let\u2019s take a simple example of computations like addition, subtraction, etc to understand the Mockito framework. <\/p>\n<p>We will create a file <i>ComputationActivity.kt<\/i> to display all computations upfront. For managing all operations we will create object class Operations.kt which will be passed to <i>ComputationActivity<\/i> class as a param in the primary constructor.<\/p>\n<pre>class ComputationActivity(private val operators: Operations) {\r\n   fun getAddition(x: Int, y: Int): Int = operators.add(x, y)\r\n   fun getSubtraction(x: Int, y: Int): Int = operators.subtract(x, y)\r\n   fun getMultiplication(x: Int, y: Int): Int = operators.multiply(x, y)\r\n   fun getDivision(x: Int, y: Int): Int = operators.divide(x, y)\r\n}\r\n<\/pre>\n<p>Operations.kt class will look like this which will handle computation functions.<\/p>\n<pre>object Operations {\r\n   fun add(x: Int, y: Int): Int = x + y\r\n   fun subtract(x: Int, y: Int): Int = x - y\r\n   fun multiply(x: Int, y: Int): Int = x * y\r\n   fun divide(x: Int, y: Int): Int = x \/ y\r\n}<\/pre>\n<p>Add dependencies needed to integrate Mockito in the build.gradle file.<\/p>\n<p>We will use <i>testImplementation<\/i> which applies to the local test source, not the application.<\/p>\n<pre>testImplementation 'junit:junit:4.13.2'\r\ntestImplementation 'org.mockito:mockito-core:2.25.0'\r\ntestImplementation 'org.mockito:mockito-inline:2.13.0'<\/pre>\n<p>Folder structure for adding <strong>ComputationTest.kt file<\/strong> for testing <strong>ComputationActivity.kt<\/strong> class.<\/p>\n<p>By default, <i>module-name\/src\/test<\/i> will be having source files for local unit tests. <\/p>\n<p><img loading=\"lazy\" decoding=\"async\" src=\"https:\/\/www.bacancytechnology.com\/blog\/wp-content\/uploads\/2022\/03\/source-files-min.png\" alt=\"source files\" width=\"1100\" height=\"92\" class=\"aligncenter size-full wp-image-25124\" srcset=\"https:\/\/www.bacancytechnology.com\/blog\/wp-content\/uploads\/2022\/03\/source-files-min.png 1100w, https:\/\/www.bacancytechnology.com\/blog\/wp-content\/uploads\/2022\/03\/source-files-min-300x25.png 300w, https:\/\/www.bacancytechnology.com\/blog\/wp-content\/uploads\/2022\/03\/source-files-min-1024x86.png 1024w, https:\/\/www.bacancytechnology.com\/blog\/wp-content\/uploads\/2022\/03\/source-files-min-768x64.png 768w\" sizes=\"auto, (max-width: 1100px) 100vw, 1100px\" \/><\/p>\n<p>Now, we will add test functions in our  ComputationTest.kt file<\/p>\n<ul class=\"bullets text-left\">\n<li><strong>@RunWith<\/strong> &#8211; we have annotated with MockitoJUnitRunner::class which means it provides the Runner to run the test.<\/li>\n<li><strong>@Mock<\/strong>&#8211; Using @Mock annotation we can mock any class. Mocking any class is nothing but to create a mock object of a particular class.<\/li>\n<\/ul>\n<p>Here we will mock the <strong>Operations.kt<\/strong> class in our test file as  <strong>ComputationActivity.kt<\/strong> file has a dependency on it.<\/p>\n<pre>@RunWith(MockitoJUnitRunner::class)\r\nclass ComputationTest {\r\n   @Mock\r\n   lateinit var operators: Operations\r\n   lateinit var computationActivity: ComputationActivity\r\n}\r\n<\/pre>\n<ul class=\"bullets text-left\">\n<li><strong>@Before<\/strong>&#8211;  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.<\/li>\n<\/ul>\n<pre>@Before\r\nfun setUp(){\r\n   computationActivity = ComputationActivity(operators)\r\n}<\/pre>\n<ul class=\"bullets text-left\">\n<li><strong>@Test<\/strong>&#8211; To perform the test we need to annotate the function with @Test.<\/li>\n<\/ul>\n<pre>@Test\r\nfun givenValidInput_getAddition_shouldCallAddOperator() {\r\n   val x = 5\r\n   val y = 10\r\n   computationActivity.getAddition(x, y)\r\n   verify(operators).add(x, y)<\/pre>\n<p>The verify method will check whether ta particular method of a mock object has been called or not.<\/p>\n<p><strong>@After<\/strong>&#8211; @After annotation is used to run after each test case completes. <\/p>\n<p><strong>@BeforeClass<\/strong>&#8211; @BeforeClass is used when you want to run a common operation that\u2019s too expensive to run multiple times. So, with this annotation, you can execute such an operation before running all other test.<\/p>\n<p><strong>@AfterClass<\/strong>&#8211; Used for deallocation of any reference after all tests executed successfully.<\/p>\n<p>Mock marker inline: Mockito can\u2019t 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. <\/p>\n<p>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 <i>Unit Testing using Mockito in Android<\/i> tutorial and run the tests. <\/p>\n<h2>Run the Tests<\/h2>\n<p>To execute all tests, right-click on ComputationTest.kt file &#038; select the option Run<\/p>\n<p>You can even run only one test function by right-clicking on that function &#038; selecting the Run option from there.<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" src=\"https:\/\/www.bacancytechnology.com\/blog\/wp-content\/uploads\/2022\/03\/Run-the-Tests-min.png\" alt=\"Run the Tests\" width=\"1100\" height=\"360\" class=\"aligncenter size-full wp-image-25123\" srcset=\"https:\/\/www.bacancytechnology.com\/blog\/wp-content\/uploads\/2022\/03\/Run-the-Tests-min.png 1100w, https:\/\/www.bacancytechnology.com\/blog\/wp-content\/uploads\/2022\/03\/Run-the-Tests-min-300x98.png 300w, https:\/\/www.bacancytechnology.com\/blog\/wp-content\/uploads\/2022\/03\/Run-the-Tests-min-1024x335.png 1024w, https:\/\/www.bacancytechnology.com\/blog\/wp-content\/uploads\/2022\/03\/Run-the-Tests-min-768x251.png 768w\" sizes=\"auto, (max-width: 1100px) 100vw, 1100px\" \/><\/p>\n<h2>Github Source: Unit Testing in Android<\/h2>\n<p>Feel free to visit the source code: <a href=\"https:\/\/github.com\/MansiKothari15\/UnitTestApplication.git\" target=\"_blank\" rel=\"noopener\">mockito-android-testing<\/a> and play around with the code!<\/p>\n<h2>Conclusion<\/h2>\n<ul class=\"bullets text-left\">\n<li><strong>Mockito is used to test final classes in Kotlin.<\/strong><\/li>\n<li><strong>Mockito is a widely used framework for mobile developers to write unit tests.<\/strong><\/li>\n<\/ul>\n<p>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!<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Introduction Nowadays mobile applications are getting complex functionalities &#038; bigger in size, that\u2019s 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 [&hellip;]<\/p>\n","protected":false},"author":22,"featured_media":25127,"comment_status":"open","ping_status":"open","sticky":false,"template":"blog-new-template.php","format":"standard","meta":{"_acf_changed":false,"inline_featured_image":false,"_lmt_disableupdate":"no","_lmt_disable":"","footnotes":""},"categories":[1364],"tags":[],"coauthors":[1608],"class_list":["post-25112","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-application-development"],"acf":[],"modified_by":"Chandresh Patel","_links":{"self":[{"href":"https:\/\/www.bacancytechnology.com\/blog\/wp-json\/wp\/v2\/posts\/25112","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.bacancytechnology.com\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.bacancytechnology.com\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.bacancytechnology.com\/blog\/wp-json\/wp\/v2\/users\/22"}],"replies":[{"embeddable":true,"href":"https:\/\/www.bacancytechnology.com\/blog\/wp-json\/wp\/v2\/comments?post=25112"}],"version-history":[{"count":0,"href":"https:\/\/www.bacancytechnology.com\/blog\/wp-json\/wp\/v2\/posts\/25112\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.bacancytechnology.com\/blog\/wp-json\/wp\/v2\/media\/25127"}],"wp:attachment":[{"href":"https:\/\/www.bacancytechnology.com\/blog\/wp-json\/wp\/v2\/media?parent=25112"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.bacancytechnology.com\/blog\/wp-json\/wp\/v2\/categories?post=25112"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.bacancytechnology.com\/blog\/wp-json\/wp\/v2\/tags?post=25112"},{"taxonomy":"author","embeddable":true,"href":"https:\/\/www.bacancytechnology.com\/blog\/wp-json\/wp\/v2\/coauthors?post=25112"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}