<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Zaid Zakir on Medium]]></title>
        <description><![CDATA[Stories by Zaid Zakir on Medium]]></description>
        <link>https://medium.com/@zaidzakir?source=rss-6b774016575------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*hObmSyPxtr_JJa379x0OQw.jpeg</url>
            <title>Stories by Zaid Zakir on Medium</title>
            <link>https://medium.com/@zaidzakir?source=rss-6b774016575------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 11:05:56 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@zaidzakir/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Testing in Android a Zero to Hero Tutorial-Part 5]]></title>
            <link>https://zaidzakir.medium.com/testing-in-android-a-zero-to-hero-tutorial-part-5-a4d3bffe9114?source=rss-6b774016575------2</link>
            <guid isPermaLink="false">https://medium.com/p/a4d3bffe9114</guid>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[espresso-testing]]></category>
            <category><![CDATA[navigation]]></category>
            <category><![CDATA[mockito]]></category>
            <dc:creator><![CDATA[Zaid Zakir]]></dc:creator>
            <pubDate>Tue, 08 Jun 2021 10:19:33 GMT</pubDate>
            <atom:updated>2021-06-08T10:19:33.608Z</atom:updated>
            <content:encoded><![CDATA[<h4>Testing Fragment/Activity interactions with Mockito &amp; Espresso continued.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PLFz420ziOejxt5ImI0h6A.png" /></figure><p><strong>Let us write a test case for scenario :</strong> when user pick on a image, from ImagePickFragment, then we navigate user back to AddShoppingFragment and make sure the image url is available in ViewModel.</p><p>We start off by first creating an image picker adapter using recycler view and diffUtils, then we create a fragment factory so to pass constructors to our fragments when needed.</p><blockquote>right click on ImagePickerFragment -&gt; generate -&gt; test case -&gt; choose androidTest folder</blockquote><h4><strong>Testing action image click in ImagePickerFragment which set image url in model view and navigate back to AddShoppingFragment</strong></h4><p>Since our fragments need constructor parameters which is supplied with the help of fragment factory we need to inject this in our test class as well, and the rest of our injections will be same as the ones in our other test classes.</p><pre>@Inject<br>lateinit var fragmentFactory: ShoppingFragmentFactory</pre><p>Now unlike our earlier test cases in which we simulated a button click with the help of onView() &amp; perform() function using espresso, simulating a click through a recycler view is a bit different.</p><p>First we need a help of another dependency which needs to be added in build.gradle() file</p><pre>androidTestImplementation &#39;androidx.test.espresso:espresso-contrib:3.3.0&#39;</pre><p>Now we have access to that function which simulates the click on a recyclerview, But this alone is not enough since we launch our fragment on a new container the data in the recyclerView will be empty. We also do not want to make any requests to our pixabay API , since it will make our test cases slow.</p><p>So we work around this by manually inserting a test url, which will satisfy our requirements.We can then check if this value matches the value from our view model. This is done is <strong>lines</strong> <strong>23,29,30 in below code block.</strong></p><p><strong>line 24- </strong>Since we don&#39;t have a MockShoppingRepositoryAndroidTest in our androidTest folder we need to create one since we cannot share things between androidTest and test folders, we can copy the one already in test folder and paste it in our folder structure so we can use its functions.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c7ac10d65d951a01bb6b425046b04a73/href">https://medium.com/media/c7ac10d65d951a01bb6b425046b04a73/href</a></iframe><p><strong>line 33 to 38-</strong> After we insert that library we have access to <strong>RecyclerViewActions.actionOnItemAtPosition&lt;”type”&gt;(“item”,”action_perform”)</strong>, which takes our viewholder type , which is of type ImageAdapter.ImageViewHolder. And then we have to pass the item we have to click on, mentioning <strong>0</strong> would mean to click on the very first item and finally we have to perform the action click()</p><p><strong>line 40</strong>- Verifies that the previous fragment (AddShoppingFragment) was opened successfully</p><p><strong>line 41</strong>- we check if the imageUrl in our mock repository contains the imageUrl we used in our test case.</p><h4>Testing functionality which will enter text in textfield and action insert the new item in database and display in list.</h4><p>We will add this test case in our already created AddShoppingFragmentTest.</p><p><strong>line 3 to 8</strong>- First we need to declare our fake viewmodel with our mock shopping repository, since the real view model will contain a actual database,Then we launch our fragment using our custom launchFragmentInHiltContainer class.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/458f9787884454e35ed5bac2694448c1/href">https://medium.com/media/458f9787884454e35ed5bac2694448c1/href</a></iframe><p><strong>line 9 to 15</strong>- using espresso we have a have a way to add text in textfield which is called replaceText(),and we perform the click as we did in earlier test cases, finally we assert that from our viewmodel the getShoppingItems data has the same values as the ones we entered above, if so then database insertion was successful and the test passes.</p><h4>Testing swipe to delete functionality</h4><p>We will experience a small adjustion when creating a test functionality for this , the reason is :</p><p>We need to allow our test cases to set view model to null, since we don&#39;t need it for test cases, but we cannot do this since our fragments instantiates our view model in the beginning of onViewCreated, and the swipe to delete functionality happens at end of fragment lifecycle.</p><pre>shoppingViewModel = ViewModelProvider(requireActivity()).<br>get(ShoppingViewModel::class.<em>java</em>)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CBXiOrRdb-gJ0l-pz2PmZw.png" /></figure><p>So to solve this we need to have a way to pass ViewModel and not declare it directly in fragment.</p><p>So to achieve the interchangeability of viewmodels between our test class and fragment class , we create another <strong>custom fragment factory</strong> for our test classes</p><p>In this new fragment factory class we will instantiate the ShoppingListFragment with a ViewModel that was created with the Mock Repository.</p><p>So we start off by handling this scenario in our ShoppingListFragment</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dc9bf1fca0921ad26c29158b23875d58/href">https://medium.com/media/dc9bf1fca0921ad26c29158b23875d58/href</a></iframe><p>In above code block we allow the shoppingViewModel to be null which can be used as a flag to tell that currently test case in use, when it does have a value it will be because a real fragment is in use.</p><p>Since we have already created a shopping fragment factory to handle our real fragment scenarios, we will copy that and paste it in the androidTest folder with one small modification.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/82338317fa84efc2f642c0f763d92026/href">https://medium.com/media/82338317fa84efc2f642c0f763d92026/href</a></iframe><p><strong>Difference in line 11 to 13-</strong> We simply just pass MockShoppingRepositoryAndroidTest() into ShoppingViewModel(), to say its a test class and in the real ShoppingFragmentFactory we don&#39;t pass anything except the adapter.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Xq0DSe3VSirbq69Njs7MIg.png" /><figcaption><strong>Real</strong> <strong>ShoppingFragmentFactory used for real app scenarios</strong></figcaption></figure><p><strong>Now we can write our test case.</strong></p><p>We have to inject the ShoppingFragmentFactoryAndroidTest , since this testing requires us to handle ViewModel appropriately.</p><pre>@Inject<br>lateinit var testFragmentFactoryAndroidTest: ShoppingFragmentFactoryAndroidTest</pre><p>test case:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a514dc746a85a5be019d48419b7e2af9/href">https://medium.com/media/a514dc746a85a5be019d48419b7e2af9/href</a></iframe><p><strong>line 3-</strong> to delete an item first we need to insert a item into our database</p><p>l<strong>ine 4-</strong> we declare a instance to our real ShoppingViewModel and set it to nullable.</p><p><strong>line 6-</strong> instead of passing our real fragmentFactory we pass our testFragmentFactoryAndroidTest</p><p><strong>line 12 to 17</strong>- we use espresso to simulate recyclerview action and use inbuilt espresso function <strong>swipeLeft() </strong>to replicate a left swipe just like our real world app scenario.</p><p><strong>line 19-</strong> and at last we check if its empty after deleting, if it is then its a successful test case.</p><p>Now when we run our test class we get :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OJagT7VZH9Ukx_ojHHmUfg.png" /></figure><p>This wraps our tutorial series if you read through till the end thank you, and i hope you were able to learn a few a things or add anything into you cavalry.</p><p>Learning testing in android is a difficult topic to say the least but a worthwhile one.</p><p>I will link my github for this complete project since i only mostly concentrated on testing and not implementation of UI and functionality</p><p>I will also link some great online references which helped me learn testing and made it a possibility to write this tutorial series to my best knowledge.</p><p>Any feedback would be appreciated</p><p><a href="https://github.com/zaidzak9/AndroidTestingSample">zaidzak9/AndroidTestingSample</a></p><p><a href="https://developer.android.com/training/testing/fundamentals">https://developer.android.com/training/testing/fundamentals</a></p><p><a href="https://developer.android.com/studio/test">https://developer.android.com/studio/test</a></p><p><a href="https://developer.android.com/training/testing/espresso">https://developer.android.com/training/testing/espresso</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a4d3bffe9114" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Testing in Android a Zero to Hero Tutorial-Part 4]]></title>
            <link>https://medium.com/geekculture/testing-in-android-a-zero-to-hero-tutorial-part-4-307417ea9abb?source=rss-6b774016575------2</link>
            <guid isPermaLink="false">https://medium.com/p/307417ea9abb</guid>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[espresso-testing]]></category>
            <category><![CDATA[dagger-hilt]]></category>
            <category><![CDATA[mockito]]></category>
            <dc:creator><![CDATA[Zaid Zakir]]></dc:creator>
            <pubDate>Tue, 08 Jun 2021 09:32:13 GMT</pubDate>
            <atom:updated>2021-06-11T11:11:00.791Z</atom:updated>
            <content:encoded><![CDATA[<p>Testing Fragments and Navigation with Dagger HILT</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PLFz420ziOejxt5ImI0h6A.png" /></figure><p>When your test cases grow at a rapid pace , object initialization will become repeated in the <strong>@ Before setup(){}</strong> function in your test classes, Example: room database.</p><blockquote>@Before fun setup(){</blockquote><blockquote>database = Room.inMemoryDatabaseBuilder( ApplicationProvider.getApplicationContext(), ShoppingItemDatabase::class.java ).allowMainThreadQueries().build()</blockquote><blockquote>dao = database.shoppingDao()</blockquote><blockquote>}</blockquote><p>A database instance is something that&#39;s often needed by several test classes. If you keep doing initialization as shown above for all your test classes, it will create a lot of boilerplate/repetitive code.</p><p>That is the reason we use Dependency Injection with Dagger-HILT so every object that’s required is defined in the App Module class.</p><p>To implement HILT we annotate @ HiltAndroidApp ,in our application class.</p><pre>@HiltAndroidApp<br>class ShoppingApplication: Application()</pre><p>But for testing this is not enough on its own,and we have to create another custom application class. and tell JUnit to use it as default class for testing</p><p>In the root of androidTest folder we will create a class called <strong>HiltTestRunner</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8df109e1e6d5b33d92d941d40fd5d94a/href">https://medium.com/media/8df109e1e6d5b33d92d941d40fd5d94a/href</a></iframe><p>We override newApplication and it returns our original application class declared in manifest , we replace that with our custom application class called<strong> HiltTestApplication::class.java.name</strong></p><p>Now we have to declare this in our test class by removing our @ Runwith(AndroidJunit4::class), as we do not need it anymore.</p><p>Since our HiltTestRunner already inherits from AndroidJunitRunner we have no need for <strong>androidx.test.runner.AndroidJUnitRunner, we can use our HiltTestRunner instead.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4HtnB--Z3cAYvra1Bz7_Uw.png" /></figure><p>In the default config replace testInstrumentationRunner with:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jb3XqIGLePfbBwjYCd4r3g.png" /><figcaption>use our new class for testInstrumentationRunner</figcaption></figure><p><strong>(your package name + hilt test runner class) -&gt; press sync now</strong></p><h4>Now we create our TestAppModule class that’s needed for dependency injection</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6c34468f9fda75720c07d08650e1a504/href">https://medium.com/media/6c34468f9fda75720c07d08650e1a504/href</a></iframe><p>4 main differences from our app module</p><ol><li>No @ Singleton annotation so that the object is created every time its required for testing</li><li>InMemoryDatabase instead of Database so its faster</li><li>Runs in main thread to avoid concurrency</li><li>@ Named annotation to be declared and inform test classes to get dependency from <strong>TestAppModule</strong> and <strong>not</strong> the <strong>real app module</strong>.</li></ol><p><strong>Now we update our ShoppingDaoTest class accordingly:</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e9f3de9d89b82717ef3d5539d3434b98/href">https://medium.com/media/e9f3de9d89b82717ef3d5539d3434b98/href</a></iframe><p><strong>line 3- @ HiltAndroidTest annotation</strong> lets android know that hilt injection is used and to take advantage of the test AppModule.</p><p><strong>line 16-</strong>database object reference gets injected with the database from <strong>test AppModule</strong>. Which is why the Named annotation is used for , its not private anymore so to allow injection.</p><p>Inside the setup function we allow injection to happen every time a test case is run.</p><h4>Testing Fragments with Dagger-HILT</h4><p>When testing fragments we use something called<strong> fragment scenarios</strong>,these fragments launch in an empty activity which is not a problem.</p><p>But since we use dagger hilt it is not straightforward,since our fragments need dependency injections ,we need to annotate these fragments with AndroidEntryPoint.Also we need to annotate the empty activity with AndroidEntryPoint</p><p>Since fragment scenario comes with a empty activity in the library,this annotation is missing in that library,So we will have create a custom activity to satisfy Dagger HILT requirements, and attach the fragment to it.</p><p><strong>First we need to add a new dependency for fragment testing</strong></p><pre>debugImplementation &quot;androidx.fragment:fragment-testing:1.4.0-alpha01&quot;</pre><p>This dependency says debugImplementation , which means it requires us to create a debug folder source set in which we will create our custom Test Activity</p><p>Inside src folder follow your default project hierarchy and create a class as shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/740/1*uWtz7tlbq1NJCKJVja7fCw.png" /></figure><p>Our new activity will hold only 2 lines of code.</p><pre>@AndroidEntryPoint<br>class HiltTestingActivity: AppCompatActivity()</pre><p>Just like any activity we have to declare this in the manifest, but we cannot use our default manifest. So we will have to create a custom manifest file to declare our custom activity.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/df77320f9c1f0973b06c06188548d779/href">https://medium.com/media/df77320f9c1f0973b06c06188548d779/href</a></iframe><p>You can copy paste your default manifest file in the root of your new debug folder,you can remove most of the code we won&#39;t need it , as shown above , we only mention android:export=”false” so to make it accessible within the debug folder only.</p><p>Now your Android folder structure should look like this,with our new debug folder in it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/740/1*qnFfxXVYnVZ6WggpBeHnGw.png" /></figure><p>Now in your AndroidTest project root we need to create a kotlin file called <strong>HiltExt.kt, </strong>this acts as a utility function for dagger hilt</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/612/1*zdux_ELwYF92Gpz4fGG57w.png" /></figure><p>Since this is a complicated function i will explain everything that happens in this function line by line.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5f510ab29eab16fab170d53e266b3438/href">https://medium.com/media/5f510ab29eab16fab170d53e266b3438/href</a></iframe><p><strong>line 7</strong>- We use inline function so it enhances the performance of our higher order function(a function which takes other functions as a parameter). The inline function tells the compiler to copy parameters and functions to the call site/required class. So the compiler does not create any objects behind the scenes , which will help your code be more memory efficient.</p><p><strong>line 7- </strong>This will be a generic function &lt;T&gt; which will inherit from fragment with help of reified, which means value will be known only at compile time.</p><p><strong>line 8-12</strong>- declare parameters</p><p><strong>line 10</strong>- allows us to later on pass data in our constructors, which will be useful with view models.</p><p><strong>line 11-</strong> used as a reference to launch hilt container with information on the fragment that’s currently being tested.</p><p><strong>line 13–20</strong>- we create a intent to start our activity in which we want to attach our fragment.Since this activity serves as the main activity, we need to make a special intent.This takes the context and class name of our activity, Since we are inside our androidTest folder we can use ApplicationProvider.getApplicationContext() , and for the class we mention the activity we created specifically for testing, and also we add a extra , allowing to define a theme.</p><p><strong>line 22</strong>- now we create our custom scenario, we launch our HiltTestActivity and pass our intent.</p><p><strong>line 23–25</strong>- We attach our fragment factory to this scenario, we first make sure that its not null.</p><p><strong>line 26–29</strong>- now we can use fragment manager to instantiate our fragment , using the androidx.core.util.Preconditions we pass our class.</p><p><strong>line 30</strong>- use the earlier reference and set the arguments to it.</p><p><strong>line 32–36</strong>- create fragment transaction to launch our fragment in that activity.</p><p>Now we can write a simple test which will take a fragment of your choice using this class to see if this works, inside the ShoppingDaoTest.class.</p><pre><strong>@Test<br>fun testLaunchFragmentInHiltContainer(){<br>    <em>launchFragmentInHiltContainer</em>&lt;ShoppingListFragment&gt;{}<br>}</strong></pre><h4>Testing navigation from ShoppingListFragment to AddShoppingFragment</h4><p>We begin by creating a nav graph and enabling navigation between these fragments.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iGfg-EXUx3_s_HYl1OFWFQ.png" /></figure><p>Let’s begin by following the same procedure of creating a test class</p><blockquote>right click on ShoppingListFragment -&gt; generate -&gt; test case -&gt; choose androidTest folder since we will need help of android components</blockquote><p>We start off by declaring the annotations, <strong>MediumTest</strong> because its integration testing, then we specify <strong>HiltAndroidTest</strong> because our test classes test the fragments which use hilt as mentioned earlier.</p><p><strong>So what are the test cases we need to do?</strong></p><p>Assert if we correctly navigate to <strong>AddShoppingFragment</strong> on click of floating button. We do that through creating mock objects which is basically a version of a class that doesn’t do anything.</p><p>Its a class which only has the function signatures,but it will keep track of how often we call its functions, and also which parameters. We also define which values it should return in each case. We will use the <strong>Mockito library</strong> for that.For the click on the floating button action we will use the<strong> Espresso library.</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8eda021a3c1f7e88cbdb081c7c806f8a/href">https://medium.com/media/8eda021a3c1f7e88cbdb081c7c806f8a/href</a></iframe><p><strong>line 16- </strong>we create a variable and use mockito library function <strong>mock()</strong> to pass our real NavController and ask it to create a mock out of it.</p><p><strong>line 18–20-</strong> use our custom class to launch fragments in activity using hilt and pass parameter with navigation.</p><p><strong>line 22- onView()</strong> is a function provided by espresso library to attach the button click to our test cases so we can simulate the action of clicking, this is passed as parameter in perform method.</p><p><strong>line 24–26- verify()</strong> is a function from <strong>mockito library</strong> which will take the <strong>action id</strong> from our nav graph which is responsible in identifying the action which will navigate from <strong>ShoppingListFragment to AddShoppingFragment</strong></p><h4>Testing navigation from AddShoppingFragment to ShoppingListFragment onBackPressed()</h4><p>Now let’s write test case to check if we really go back to our shopping fragment onBackPressed.</p><blockquote>right click on AddShoppingFragment -&gt; generate -&gt; test case -&gt; choose androidTest folder</blockquote><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f4e48933ddb8bee30538b977abc3ac01/href">https://medium.com/media/f4e48933ddb8bee30538b977abc3ac01/href</a></iframe><p>The only difference here is</p><p><strong>line 20-</strong> a function in espresso library to replicate onBackPress() button click in testing class.</p><p><strong>line 21- </strong>function to verify if popBackStack was successful</p><p><a href="https://zaidzakir.medium.com/testing-in-android-a-zero-to-hero-tutorial-part-5-a4d3bffe9114"><strong>Testing in Android a Zero to Hero Tutorial-Part 5</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=307417ea9abb" width="1" height="1" alt=""><hr><p><a href="https://medium.com/geekculture/testing-in-android-a-zero-to-hero-tutorial-part-4-307417ea9abb">Testing in Android a Zero to Hero Tutorial-Part 4</a> was originally published in <a href="https://medium.com/geekculture">Geek Culture</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Testing in Android a Zero to Hero Tutorial-Part 3]]></title>
            <link>https://medium.com/geekculture/testing-in-android-a-zero-to-hero-tutorial-part-3-b1a3b5504965?source=rss-6b774016575------2</link>
            <guid isPermaLink="false">https://medium.com/p/b1a3b5504965</guid>
            <category><![CDATA[mockito]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[mvvm]]></category>
            <category><![CDATA[android-testing]]></category>
            <dc:creator><![CDATA[Zaid Zakir]]></dc:creator>
            <pubDate>Tue, 08 Jun 2021 08:51:52 GMT</pubDate>
            <atom:updated>2021-06-11T11:11:04.060Z</atom:updated>
            <content:encoded><![CDATA[<p>Testing View Model and Repository</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PLFz420ziOejxt5ImI0h6A.png" /></figure><blockquote>For this tutorial i used api from <a href="https://pixabay.com/api/docs/">https://pixabay.com/api/docs/</a> to demonstrate Networking with Retrofit API calls.</blockquote><p>I will not go through setting up retrofit and dagger hilt , below i have linked the files to all the setup.</p><p><a href="https://github.com/zaidzak9/AndroidTestingSample">zaidzak9/AndroidTestingSample</a></p><p>You know by now that test cases have to be fast, but network calls are anything but that. So to write test cases for Network calls we need the help of test doubles, what this means is , we will create a real repository where our app accesses apis and a fake/mock repository to be used in our test cases.</p><h4>Let’s start by implementing the Shopping repository</h4><p>To create a test double we need to first implement a repository interface in which all our suspend functions are declared, in short the necessary function that is needed by our Room DB and retrofit calls to manipulate/access data, this interface will then be inherited by our <strong>test repository</strong> and our <strong>real repository(aka default repository).</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/23468cf24185e77793f358a92972725e/href">https://medium.com/media/23468cf24185e77793f358a92972725e/href</a></iframe><p>Since we are using <a href="https://zaidzakir.medium.com/a-simple-android-app-using-mvvm-dagger-hilt-e9f45381f1bc"><strong>dagger HILT for dependency injection</strong></a> in this tutorial , i will make modifications to our previously implemented Room DB as well to update it with dagger HILT. The Shopping repository interface now has all the functions which is needed by the app for data access.</p><p><strong>Below is the Default Repository which will be used by the actual app to make api calls and access the database.</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0e53a49a593ff3f23786cf565566549d/href">https://medium.com/media/0e53a49a593ff3f23786cf565566549d/href</a></iframe><p><strong>Now we will create the Mock Repository inside the Test Folder , We have to always make sure that our folder structure in androidTest folder and test folder matches that of our main folder structure.</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8e9c9e9c03b33274f710f65941079fd2/href">https://medium.com/media/8e9c9e9c03b33274f710f65941079fd2/href</a></iframe><p><strong>Breakdown of MockShoppingRepository</strong></p><p>The main purpose of the <strong>MockShoppingRepository </strong>is to test the viewmodel later on , we only create this repository to pass to our viewmodel to emulate our test cases since we cant use the <strong>default repository</strong>,we will pass the Shopping repository in the constructor of the view model allowing our viewmodel to inherit the real and mock repositories when needed</p><pre>private val shoppingItems = <em>mutableListOf</em>&lt;ShoppingItem&gt;()</pre><p>Below we create a list of shopping items which we will use to populate data into so we can emulate the behaviour of our database shopping items.</p><pre>private val observableShoppingItems = MutableLiveData&lt;List&lt;ShoppingItem&gt;&gt;(shoppingItems)</pre><pre>private val observableTotalPrice = MutableLiveData&lt;Float&gt;()</pre><p>Below we create the MutableLiveData for observableShoppingItems and observableTotalPrice to observe from our view model just like our real repo.</p><pre>private var shouldReturnNetworkError = false<br><br>fun setShouldReturnNetworkError(value: Boolean) {<br>    shouldReturnNetworkError = value<br>}</pre><p>Since we don’t use network calls,we need a value to emulate how our view model will work when network is available and when it is not , this allows us to check how our app works in both environments.</p><p>Just as in our default repository we will go ahead and inherit from the shopping repository interface and get all the methods to finish our class.</p><pre>private fun refreshLiveData() {<br>    observableShoppingItems.postValue(shoppingItems)<br>    observableTotalPrice.postValue(getTotalPrice())<br>}</pre><p>To correctly simulate the behaviour of our live data objects here we need to post the new value after we add items to the list, that is why we need the <strong>refreshLiveData()</strong> function as shown above.</p><h4>Preparing ViewModel for Testing</h4><pre>@HiltViewModel<br>class ShoppingViewModel @Inject constructor(<br>    private val repository: ShoppingRepository<br>): ViewModel(){}</pre><p>When preparing the ShoppingViewModel for testing we have to make sure we pass the interface shopping repository in the constructor so to make it compatible for our default repository and mock repository to access it, in that case it will be easily interchangeable for both, since both those classes inherit from ShoppingRepository.</p><p><strong>Generic Event Class</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4200cdf46fc20085331bbca0b3d34091/href">https://medium.com/media/4200cdf46fc20085331bbca0b3d34091/href</a></iframe><p>Now we need a help of a class to make sure our livedata emit one time events , because we often have the problem when we make a network request to our server and with resource class we either emit <strong>success</strong> or <strong>error </strong>in the live data object.</p><p>The problem that could arise from this is let&#39;s say if an error occurred while in portrait mode and user rotates the device, Live data will emit the same data again causing the same message to be shown twice.</p><p><strong>getContentIfNotHandled()</strong> this function will emit data only for the first time it is called, 2nd time onwards it will return null.</p><p>Since testing view model is a part of unit test we will create only the function signature and write test cases for them first in respect to TDD.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/54787cb822cc7d5707d9e82f0bc48292/href">https://medium.com/media/54787cb822cc7d5707d9e82f0bc48292/href</a></iframe><p>Define two constants to be used in checking length of <strong>ITEM_NAME</strong> &amp; <strong>ITEM_PRICE</strong> in our constant class</p><pre>const val MAX_ITEM_NAME_LENGTH = 20<br>const val MAX_ITEM_PRICE_LENGTH = 10</pre><p>Since we don’t provide a default Shopping repository injection for our viewmodel, we have to create a default shopping repository and cast that to shopping repository</p><pre>@Singleton<br>@Provides<br>fun provideDefaultShoppingRepository(<br>    dao: ShoppingDao,<br>    api: PixabayAPI<br>) = DefaultShoppingRepository(dao, api) as ShoppingRepository</pre><p>Now Dagger Hilt will know the injections that’s needed for our viewmodel.</p><p>Finally we instantiate our View Model in all of our fragments.</p><p>example:</p><pre>lateinit var shoppingViewModel: ShoppingViewModel</pre><pre>onViewcreated(){<br>shoppingViewModel = ViewModelProvided(requireActivity()).<br>get(ShoppingViewModel::class.<em>java</em>)<br>}</pre><p><strong>requireActivity()</strong> binds our viewmodel to our activity.</p><h3>Testing our View Model</h3><blockquote><strong>ShoppingViewModel -&gt; Right Click -&gt; Generate Test Case -&gt; Junit 4 -&gt; test folder -&gt; Create file named ShoppingViewModelTest</strong></blockquote><p>Testing view models doesn’t require any android components, so we go with the test folder.</p><pre>lateinit var viewModel: ShoppingViewModel</pre><p>We initialize our <strong>ShoppingViewModel</strong> to be used right through out out test view model class</p><pre>@Before<br>fun setup(){<br>    viewModel = ShoppingViewModel(MockShoppingRepository())<br>}</pre><p>Now we initialize that to <strong>ShoppingViewModel</strong> and pass the <strong>MockShoppingRepository() </strong>and now we need only a list of data, instead of the default repository in which we will have to pass the api and the dao class as in the picture below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VEHG4ZC_fyo61mPU7-Za4g.png" /><figcaption>why we should not use the default repository for testing</figcaption></figure><h4>Let’s write some ViewModel Test cases</h4><ol><li>A case to test if the data to insert a item in db has any missing fields, if it does , our expected response should be an error, if all goes by plan our test will pass</li></ol><p><strong>.getOrAwaitValueTest() </strong>is from the class <strong>LiveDataUtil</strong>, we cannot use the class we created earlier for androidTest so we will have to copy paste it into our test folder to make it accessible.</p><p><strong>assertThat()</strong> will retrieve the status from our event class and check if the status is equal to <strong>Status.ERROR</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a7edd296801ba6dec3aa44a955035d73/href">https://medium.com/media/a7edd296801ba6dec3aa44a955035d73/href</a></iframe><p>2. A function to test if the entered name length exceeds that of our value in the constants file, if so return error, test case should pass , else fail, to achieve this we use the help of kotlin lambda function buildString which will build us a string dynamically with length in size of CONSTANTS.MAX_LENGTH +1, rather than we having to statically type it. In this case we will not have to update our test functions and classes every time we make a change.</p><p>3. Also below that we will write an exact same function but this time to test how long our price length is.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f83f1ed863d0f80615eb792c2e1fae83/href">https://medium.com/media/f83f1ed863d0f80615eb792c2e1fae83/href</a></iframe><p>3.Finally we wrap it up by writing the last 2 cases which will check if amount entered is a invalid int , we have to make sure the number entered doesn’t exceed that of what a int value could hold,and we write a test to check if insert into db is success if we enter correct item details.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f007c55cabf4e81306d1b186b187a0a6/href">https://medium.com/media/f007c55cabf4e81306d1b186b187a0a6/href</a></iframe><p>Now when we run this you will end up with few errors which will need some explanations before solving</p><p><strong>Error 1</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*75-67rTiRWNKyWjUq_BS9Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nMdMBnuUG7FiS1J5m65PRA.png" /></figure><p>If you face this, then click on default and select JAR manifest and press ok.</p><p><strong>Error 2</strong></p><p>Now when you run this again we get another error but this time it’s because we have not used the <strong>InstantTaskExecutorRule </strong>, just like in androidTest, this will allow all test cases to run one after the other in the same thread.</p><blockquote><strong>@get:Rule<br>var instantTaskExecutorRule = InstantTaskExecutorRule()</strong></blockquote><p><strong>Error 3</strong></p><p>And also since our liveData doesn’t emit a value which test cases expect since we don&#39;t post anything yet because the function implementation in our view model was never finished since we follow TDD, so to solve this we will have to finish up our function implementations in our real view model class.</p><blockquote><strong>java.util.concurrent.timeoutexception : LiveData was never set</strong></blockquote><p><strong>Complete View Model Class implementation</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/87d0081645760c0a3ea9d67c351e0067/href">https://medium.com/media/87d0081645760c0a3ea9d67c351e0067/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cOukSfzB1o8PHOZGYB-wFw.png" /></figure><p><strong>Error 4</strong></p><p>Now when we run our test class, our test cases run and pass successfully, but we end with a unusual error</p><blockquote><strong>Exception in thread “main” java.lang.IllegalStateException: Module with the Main dispatcher had failed to initialize. For tests Dispatchers.setMain from kotlinx-coroutines-test module can be used</strong></blockquote><p><em>What is this?</em></p><p>The reason why it failed is if you look at our <strong>ShoppingViewModel</strong> class we use a coroutine inside our<strong> fun validateShoppingItem(name: String, amount: String, price: String){}</strong> function, and this calls our <strong>insertItemsIntoDb()</strong> function and this uses a suspend function, and that uses the Main Dispatcher which relies on the Main Looper which is only available in a real app scenario</p><p>Since we run this test in our JVM we don&#39;t have access to a real apps environment like in androidTest folder which has access to Main Dispatcher.</p><p>So to solve this we need to create our own JUnit Rule.</p><p>In the root of your test folder create a class called <strong>MainCoroutineRule</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c4ecbebf68636b9114ea5c539d5d71a2/href">https://medium.com/media/c4ecbebf68636b9114ea5c539d5d71a2/href</a></iframe><p>In the constructor we pass the dispatcher and set it by default to <strong>TestCoroutineDispatcher</strong> which is the recommended dispatcher for test cases,and that will inherit from <strong>test watcher </strong>which will enable this class to be recognized as a rule by <strong>JUnit test</strong>.</p><p><strong>override fun starting</strong> will allow our test dispatcher to replace main dispatcher when needed, and then <strong>override fun finished</strong> will reset everything once job is done.</p><p>Now in our <strong>ShoppingViewModelTest</strong> we apply our new rule and re-run our tests</p><pre>@get:Rule<br>var mainCoroutineRule = MainCoroutineRule()</pre><p>Once we re-run, all our tests will pass and no errors will be shown as our view model test class is now complete.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LInc1LNPK2zOPF48xxfHLg.png" /></figure><p><a href="https://zaidzakir.medium.com/testing-in-android-a-zero-to-hero-tutorial-part-4-307417ea9abb"><strong>Testing in Android a Zero to Hero Tutorial-Part 4</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b1a3b5504965" width="1" height="1" alt=""><hr><p><a href="https://medium.com/geekculture/testing-in-android-a-zero-to-hero-tutorial-part-3-b1a3b5504965">Testing in Android a Zero to Hero Tutorial-Part 3</a> was originally published in <a href="https://medium.com/geekculture">Geek Culture</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Testing in Android a Zero to Hero Tutorial-Part 2]]></title>
            <link>https://medium.com/geekculture/testing-in-android-a-zero-to-hero-tutorial-part-2-577aeb79ae14?source=rss-6b774016575------2</link>
            <guid isPermaLink="false">https://medium.com/p/577aeb79ae14</guid>
            <category><![CDATA[mockito]]></category>
            <category><![CDATA[espresso-testing]]></category>
            <category><![CDATA[coroutine-testing]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[roomdb]]></category>
            <dc:creator><![CDATA[Zaid Zakir]]></dc:creator>
            <pubDate>Tue, 08 Jun 2021 08:33:44 GMT</pubDate>
            <atom:updated>2021-06-11T11:11:06.849Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PLFz420ziOejxt5ImI0h6A.png" /></figure><p>In this part we look at testing <strong>android components,@Before and @After</strong> concepts and how we can <strong>test Room DB</strong>.</p><p>In the previous tutorial we created a function and test case which can run using the JVM inside the test folder, now lets work on another example that requires a context and checks if string from resource file matches with string from user input.</p><p><strong>Let’s get started</strong></p><p>This time we will create a kotlin class, in this case we will need a instance of this class in our test case. So go ahead and create <strong>CompareStrings.kt</strong> class, which takes the context , resource string id and user input string.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e9c08e341377a82c88d28749f475a843/href">https://medium.com/media/e9c08e341377a82c88d28749f475a843/href</a></iframe><p>Just like in the last tutorial we create a test class by</p><ul><li>right clicking on the name</li><li>choosing junit 4 and a suitable name</li><li>and this time we choose androidTest folder instead of test folder</li></ul><p>We choose <strong>androidTest</strong> folder because we need to get the reference of the context object, unlike last time , we also need the instance of the our class CompareStrings.kt</p><p>Let’s do this test case using bad practice first , and i will explain why this is bad practice 👎</p><p>Unfortunately the naming convention we used in the test directory does not work for the androidTest directory, many answers regarding as to why can be found in this <a href="https://stackoverflow.com/questions/46295418/cannot-use-kotlin-backticked-method-names-in-androidtest-bad-descriptor-except">stackoverflow question</a>, hopefully when your reading this there is a solution,you can choose to have the same naming convention in both folders or different, it is up to you. Nevertheless here is the bad practice explained below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/214ef3780bdf82cc20730a11c4a66ef2/href">https://medium.com/media/214ef3780bdf82cc20730a11c4a66ef2/href</a></iframe><p>This above test class we create test case to check if both string matches and if does return true and if it does not then return false , works fine, but why is this bad practice? 😕</p><p>All of our test cases should run independent of each, but in this example above ,they rely on shared instance of the class compare string , this is bad because let’s imagine if we have a function which has a counter member variable.</p><p>and if we have 2 test cases in which case A increments the counter by 1 and case B starts from 1, since we do not have a order at which test cases are run by first as in our bad practice example this could produce <a href="https://engineering.atspotify.com/2019/11/18/test-flakiness-methods-for-identifying-and-dealing-with-flaky-tests/#:~:text=A%20flaky%20test%20is%20a,new%20builds%20to%20complete%20successfully.">flaky tests</a>(sometimes fails sometimes succeeds).</p><p><strong>Best practice answer now</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3fc77fab269b111f18e894df3dad3c76/href">https://medium.com/media/3fc77fab269b111f18e894df3dad3c76/href</a></iframe><p>The object reference issue can be solved by using the annotation <strong>@Before</strong> and <strong>@After .</strong></p><p><strong>@Before</strong>- a function which uses this will run before any test case runs therefore creating new instances everytime and allowing the test case to run on a clean slate, because you don’t want to be creating a new instance for compare string class and context in every test case, this will create a lot of redundant code.</p><p><strong>@After</strong>- is used to clean up after all your test cases are finished running, we don’t need this in this example since we have no use for this,since garbage collection handles context. But this is quite commonly used in testing Room DB which we will look at next.</p><h4><strong>Testing Using Real Application</strong></h4><p>Before starting i am going to assume you already know how MVVM,LiveData,Dagger HILT,Retrofit,Room DB and Coroutines work, since this tutorial is only going to concentrate on testing.</p><p><a href="https://zaidzakir.medium.com/coroutines-in-android-explained-8f00a37c8528">&gt;&gt;&gt;Click here for my article on Coroutine&lt;&lt;&lt;</a></p><p>This tutorial series on testing is based on a simple application i created to manage shopping list items,uploaded on my github, we will use it for our examples, all implementations have been completed and we will only look at testing was done.</p><p>Functionalities include:</p><ul><li>MVVM,Live Data, Coroutines,Dagger HILT</li><li>Insert items to Room DB</li><li>Network calls made with Retrofit and Pixabay API</li><li>Recycler Views,Swipe to delete</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7ZYFMTN389YBvSXMbnwoBg.png" /></figure><p><a href="https://github.com/zaidzak9/AndroidTestingSample">zaidzak9/AndroidTestingSample</a></p><p><strong>Switch off Animation while testing</strong></p><p><a href="https://developer.android.com/training/testing/espresso/setup#set-up-environment">This best practice is recommended by google</a></p><blockquote>To avoid flakiness, we highly recommend that you turn off system animations on the virtual or physical devices used for testing. On your device, under <strong>Settings &gt; Developer options</strong>, disable the following 3 settings:</blockquote><ul><li>Window animation scale</li><li>Transition animation scale</li><li>Animator duration scale</li></ul><p>Now let’s look at how we can test our Room Database , testing a room database requires help of <strong>Android Components such as context and memory</strong> so we will have to create a test class in androidTest folder.</p><p>Always remember that our folder structure in test or androidTest should follow the same structure as our main structure which contains android code.</p><p>Since our original shoppingDao is a interface , we cannot create test classes for interface by right clicking as done in earlier examples.</p><p>We have to manually create a test class in the androidTest folder, <strong>right click -&gt; kotlin file/class -&gt; create class</strong></p><pre>@RunWith(AndroidJUnit4::class)<br>class ShoppingDaoTest {<br><br>}</pre><p>So once we create our class like above we add the annotation <strong>@RunWith(AndroidJUnit4::class)</strong> , generally any java or kotlin code needs JVM to run , since this is by default included in our test folder, this is not included in androidTest folder because we are inside the android environment, so to enable this we have to include that annotation shown above.</p><h4>Types of Test annotations</h4><blockquote>Test size qualifiers are a great way to structure test code and are used to assign a test to a test suite of similar run time.</blockquote><p><strong>@ SmallTest</strong>-Small tests should be run very frequently. Focused on units of code to verify specific logical conditions. These tests should run in an isolated environment and use mock objects for external dependencies. Resource access (such as file system, network, or databases) are not permitted.Tests that interact with hardware, make binder calls, or that facilitate android instrumentation should not use this annotation.</p><p><strong>@ MediumTest</strong>- Medium tests should be focused on a very limited subset of components or a single component.Resource access to the file system through well defined interfaces like databases,ContentProviders, or Context is permitted. Network access should be restricted, (long-running)blocking operations should be avoided and use mock objects instead.</p><p><strong>@ LargeTest</strong>- Large tests should be focused on testing integration of all application components. These tests fully participate in the system and may make use of all resources such as databases, file systems and network. As a rule of thumb most functional UI tests are large tests.</p><p><strong>For this class we use @ MediumTest</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/424883548189455d9a78a900e2fd221c/href">https://medium.com/media/424883548189455d9a78a900e2fd221c/href</a></iframe><ul><li><strong>line 5 &amp; 6-</strong> We have created references to our <strong>ShoppingItemDatabase</strong> and <strong>ShoppingDao</strong> classes.</li><li><strong>line 8 to 16-</strong> Now we use the function setup with <strong>@ Before</strong> annotation to make sure new instances of RoomDB and ShoppingDao is needed for each test case so there is a complete independency between test cases and no kind of data manipulation to produce flaky tests.</li><li><strong>line 10- Room.inMemoryDatabaseBuilder</strong> is used to instruct the system to use memory in ram for storing data rather than persistence memory so that we can have a new database for each test case</li><li>In normal circumstances we allow functions such as network calls and database calls to run in background thread so the UI isn’t interrupted or ANR crashes isn’t caused, but when writing test cases we specifically instruct the test cases to be run in the main thread to disallow any sort of manipulation, you do not want Test A and Test B to run at the same time and manipulate the DB in different ways which will result in flaky tests.</li><li><strong>line 18 to 21- </strong>In the previous example we were not able use the <strong>@ After</strong> annotation since it was not needed, but in case of a database it’s very much necessary as we need to close the database after every test is complete.</li></ul><h4>So now we can begin writing our test case to test if Shopping items are being inserted correctly into Room DB.</h4><p>Since the insert function in our interface is a <strong>suspend function</strong> , we need <strong>coroutines</strong> to run it, but then coming back to my earlier point, we cannot use any form of concurrency when it comes to test cases, so to satisfy both these requirements , we can use a coroutine lambda function called runBlockingTest { }<strong>, </strong>you might have heard of<strong> </strong>runBlocking { } ,whose purpose is that the thread that runs it (main thread) gets <em>blocked</em> for the duration of the call, until all the coroutines inside runBlocking { } complete their execution. the runBlockingTest does the similar thing but is modified to suit test cases.it will immediately progress past delays and into launch and async blocks. You can use this to write tests that execute in the presence of calls to delay without causing your test to take extra time.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/02ec9c4e416365015059bd1f2176fb54/href">https://medium.com/media/02ec9c4e416365015059bd1f2176fb54/href</a></iframe><p><strong>line 3</strong>- we create a shopping item using our data class .</p><p><strong>line 4</strong>- we use the dao reference and access the insert suspend function in our interface.</p><p><strong>line 6</strong>-after inserting we need to confirm if the data we inserted was actually successful, to do this we use the observeAllShoppingItems() method, but this returns a liveData, this takes us back to the concurrency issue/argument ,we cannot have this in our test cases, so to get around this issue we can use a pre built class by google called <a href="https://developer.android.com/codelabs/advanced-android-kotlin-training-testing-basics#8"><strong>LiveDataUtilAndroidTest</strong></a></p><blockquote>You can just copy-paste this class in your project androidTest root folder, what this class does is observes a LiveData until it receives a new value (via onChanged) and then it removes the observer. If the LiveData already has a value, it returns it immediately. Additionally, if the value is never set, it will throw an exception after 2 seconds (or whatever you set). This prevents tests that never finish when something goes wrong.</blockquote><p>Above explanation taken from article linked below, read more for a very detailed explanation.</p><p><a href="https://medium.com/androiddevelopers/unit-testing-livedata-and-other-common-observability-problems-bb477262eb04">Unit-testing LiveData and other common observability problems</a></p><p><strong>line 8</strong>- now we use the assertThat from google truth library and check if that insert item exists in the database</p><p>Now when you press play and run this program you will likely get an error saying</p><blockquote><strong>java.lang.IllegalStateException: This job has not completed yet</strong></blockquote><p><strong>What this means is</strong></p><p>This exception is caused by our live data, because it’s asynchronous by default and even though we use runBlockTest{} JUnit doesn’t allow that and to solve that problem we need to declare a Rule to explicitly tell JUnit to execute all of the code inside the test class one by one on the same thread</p><pre><strong>@get:Rule<br>var instantTaskExecutorRule = InstantTaskExecutorRule()</strong></pre><p>Now when you re-run it,it will be successful.</p><p>Now lets go ahead and finish the rest of the test cases, pretty similar to above one and self explanatory.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ebef0d13ff5b348df0cce21c1fbeaaa5/href">https://medium.com/media/ebef0d13ff5b348df0cce21c1fbeaaa5/href</a></iframe><p>We don’t have to worry of data being mismatched, since every time a test case runs a new instance of database is created</p><p>The only difference in above test cases is how we use the assertThat() to get our required result.</p><blockquote><strong>deleteShoppingItem() : First we insert a item so that we have something to delete, we go ahead and delete that item after inserting and then check if database is empty to confirm its been deleted.</strong></blockquote><blockquote><strong>observeAllShoppingItem() : We insert an item and check if the size of the database is 1.</strong></blockquote><blockquote><strong>observeTotalPrice(): we enter 3 items and calculate in assertThat if our total number matches the prices we entered.</strong></blockquote><p>This was a basic overview for Testing in Room Database, in the next tutorial let’s have a look at how we can test <strong>Retrofit with Dagger HILTs</strong></p><p><a href="https://zaidzakir.medium.com/testing-in-android-a-zero-to-hero-tutorial-part-3-b1a3b5504965"><strong>Click here for Testing in Android a Zero to Hero Tutorial-Part 3</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=577aeb79ae14" width="1" height="1" alt=""><hr><p><a href="https://medium.com/geekculture/testing-in-android-a-zero-to-hero-tutorial-part-2-577aeb79ae14">Testing in Android a Zero to Hero Tutorial-Part 2</a> was originally published in <a href="https://medium.com/geekculture">Geek Culture</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Testing in Android a Zero to Hero Tutorial -Part 1]]></title>
            <link>https://medium.com/geekculture/testing-in-android-a-zero-to-hero-tutorial-part-1-b2f3a7a2b6b2?source=rss-6b774016575------2</link>
            <guid isPermaLink="false">https://medium.com/p/b2f3a7a2b6b2</guid>
            <category><![CDATA[test-driven-development]]></category>
            <category><![CDATA[mockito]]></category>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[espresso-testing]]></category>
            <dc:creator><![CDATA[Zaid Zakir]]></dc:creator>
            <pubDate>Tue, 08 Jun 2021 08:28:16 GMT</pubDate>
            <atom:updated>2021-06-08T13:03:53.196Z</atom:updated>
            <content:encoded><![CDATA[<p>What is Android Testing with simple example</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PLFz420ziOejxt5ImI0h6A.png" /></figure><p>This tutorial series will cover all the necessary things you need to know about testing in android using a working example from my <a href="https://github.com/zaidzak9/AndroidTestingSample">github</a>.</p><ul><li><strong>JUnit / Mockito / Espresso / Google Truth Library</strong></li><li><strong>TDD with Simple examples</strong></li><li><strong>Room DB/Retrofit Network using with Pixabay Api</strong></li><li><strong>Dagger-HILT</strong></li><li><strong>MVVM</strong></li><li><strong>Fragments &amp; Navigation</strong></li></ul><p><a href="https://github.com/zaidzak9/AndroidTestingSample">zaidzak9/AndroidTestingSample</a></p><p>We are required to write test cases in our android apps so that we are able to test code instantly from scratch with single button click on a regular basis.This helps us keep our code bug free most of the time.</p><p><strong>Let&#39;s get started</strong></p><p>Below is the testing pyramid</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bBa99biSpI9BsaVdnzOMQw.png" /><figcaption>image from <a href="https://developer.android.com/training/testing/fundamentals">https://developer.android.com/training/testing/fundamentals</a></figcaption></figure><p>Your test cases will need the help of either the <a href="https://developer.android.com/studio/intro/studio-config"><strong>J.V.M</strong></a> , <a href="https://developer.android.com/studio/run/emulator"><strong>Android Emulator</strong></a> or both. Test cases which need an emulator are usually slow because they need the help of android components to run, which is why it takes up the smaller portions of the triangle, the biggest portion is taken up by the test cases using mostly JVM which are unit tests.</p><p><strong>Unit Tests</strong> <strong>-</strong>are the fastest tests in our program , they usually run in a few milliseconds,its used to test functions such as checking if username matches the function validation or a function which calculates the sum of some integers, The reason it works fast is because it does not depend on any components such as UI or network simulation and only tests logic.</p><p><strong>Integration Tests- </strong>run with the help of the emulator which makes it slower than unit tests, an example of this test could be testing the communication between a fragment and viewmodel or replicating a network call.</p><p><strong>UI Tests</strong>-Tests a complete round of user interactions involving the example taken from the my github project is adding a shopping item and checking if its entered in the DB, this type of tests should take the smallest portion since the emulator needs to be created and run through the UI. UI test do not have to be on top of our pyramid because they act as a sidekick to the other 2.</p><h3><strong>Test Driven Development (TDD)</strong></h3><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FwN4GIuq6mjMGzMuhxf%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FwN4GIuq6mjMGzMuhxf%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2FwN4GIuq6mjMGzMuhxf%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="244" frameborder="0" scrolling="no"><a href="https://medium.com/media/79b209f2f7aadab8b0bf393405cae075/href">https://medium.com/media/79b209f2f7aadab8b0bf393405cae075/href</a></iframe><p><strong>No 1 theory of TDD best practice is</strong></p><blockquote><strong><em>“Write test cases before the function implementation”</em></strong></blockquote><p>These are steps to follow</p><ul><li>Write your function signature</li><li>Write test case for what that function is going to do and what you expect from it .</li><li>Write function logic so test case passes.</li></ul><blockquote><em>This procedure is carefully followed when writing </em><strong><em>unit tests </em></strong><em>and recommended for </em><strong><em>Integration and UI testing </em></strong><em>as well.</em></blockquote><p>Each of your test cases should try to contain only a single <a href="https://en.wikipedia.org/wiki/Test_assertion">assertition</a> at best, assertion is what decides the outcome of a particular test case , this could either be true or false, but in rare cases you might need more like checking if object in null.</p><p>But the problem of having multiple assertions is it makes our test cases dependent on other test cases or outcomes, and the goal is to make test cases independent as possible, why u ask? well it’s so that if something goes wrong we need to be able to identify the cause as quickly as possible and avoid checking the test cases unless we really need to.</p><h4><strong>What makes a good test case?</strong></h4><p><strong>Scope</strong>-How much code your test case covers</p><p><strong>Speed</strong>- How fast your test case runs, the faster it runs the more often you will run it , find bugs and fix them</p><p><strong>Fidelity</strong>- Making sure your test cases are as accurate as possible with a real world scenario.</p><p><strong>Avoid flaky tests</strong>- flaky tests are tests that emit different outcomes at different moments, example : imagine a function that generate a random number between to 1–10 , if the success of your test depends on you getting 5,6,7 then it’s going to fail the rest of the times .Flaky tests could depend on other factors as well not only this example. We will dig deeper into these topics later on.</p><p>So this is why it is important to make test cases independent and not write test cases that depends on other test case outcomes.</p><h4><strong>Equivalent class theory</strong></h4><blockquote>It’s important to write test cases and also write as less test cases as possible.</blockquote><p>Equivalent class theory means a single outcome to a certain feature,Take an example such as a registration form with username , password and confirm password. The equivalent class of this page is a successful registration , so to emulate a successful registration we need to check the validity of the username, password , check if password matches with confirm password and also check if username does not already exist, to do all these we need to write as less test cases as possible , it does not matter if test case passes with 2 valid usernames such as “username1” or “username2” since it produces the same outcome , it is unnecessary to test both of the inputs individually ,since both will produce the same outcomes .</p><p>We looked at the theory of testing and its principles.now let’s get into some basic coding examples and explanations.</p><h4><strong>Writing our first Unit Test</strong></h4><p>By default when we create a android project we have 3 dependencies related to testing existing by default in our gradle.</p><pre><strong>testImplementation</strong> <strong>&quot;junit:junit:4.13.2&quot;</strong><br><strong>androidTestImplementation</strong> <strong>&#39;androidx.test.ext:junit:1.1.2&#39;</strong><br><strong>androidTestImplementation</strong> <strong>&#39;androidx.test.espresso:espresso-core:3.3.0&#39;</strong></pre><ul><li>JUnit is an android testing framework</li><li>Espresso is a dependency that is needed for UI and Integration tests.</li></ul><p>We will need to a couple of extra dependencies.</p><pre><strong><em>androidTestImplementation</em></strong> <strong>&quot;com.google.truth:truth:1.1.2&quot;</strong><br><strong><em>testImplementation</em></strong> <strong>&quot;com.google.truth:truth:1.1.2&quot;</strong></pre><p>This is a library made by google to make our <a href="https://en.wikipedia.org/wiki/Test_assertion">assertions</a> much more readable.</p><p><strong>So what is the difference between testImplementation and androidTestImplementation why did we insert it twice?</strong></p><p>If you are someone who is new to testing, then have you ever asked yourself what those 2 extra folders highlighted(androidTest &amp; test) mean whenever you create a new project?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/430/1*YYvv9wfXISilXgqJTSfoEA.png" /></figure><p>In part 1 we discussed what Unit tests , Integrated tests and UI tests is ,their pros and cons on when and why it is needed.</p><p>Your I<strong>ntegration and UI </strong>test cases which need the help of your <strong>emulator</strong> and <strong>android components</strong> will go into <strong>androidTest</strong> <strong>folder</strong> and the <strong>unit tests</strong> which run on the J.V.M and does not need the help of your <strong>emulator</strong> or any <a href="https://developer.android.com/reference/android/content/Context"><strong>contexts</strong></a> will go into the <strong>test folder.</strong></p><p>The reason we input same dependency twice is we are making it accessible for the test cases in <strong>androidTest</strong> and <strong>test</strong> folders.</p><p>Below i have created an object class in our android kotlin project, the purpose of this class and its registerUser function is to validate user input in a registration form.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1a04a59b09d9dc0938773557852bb6e4/href">https://medium.com/media/1a04a59b09d9dc0938773557852bb6e4/href</a></iframe><p>Since we are following TDD for this unit test the first thing we need to do is create the function signature and write the set of rules which will allow it to pass.</p><p><strong>So now lets go ahead and create out Unit Test case</strong> 👌</p><p>Right click on your RegistrationForm class name and select <strong>Test…</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/736/1*CIH9D7C-Fzee-ea0SysMbg.png" /></figure><p>Now press the testing library dropdown and select <strong>JUnit 4</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GWNEL0vgtvNLE2xAp3lf4Q.png" /></figure><p>Once we press ok we are prompted to select the folder this file needs be to saved in, since this is a unit test and we do not need the help of the emulator and only need the JVM we will select the<strong> test folder.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/902/1*PTa62PHqvu0xZ6QcVINQog.png" /></figure><p>Android will now create a test class inside the test package where we will write our first test case, this test case simply checks if the username is empty or not.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d2f2b495009adafa8479b9d892b7bc3a/href">https://medium.com/media/d2f2b495009adafa8479b9d892b7bc3a/href</a></iframe><p><strong>line 5- Annotation , </strong>When writing out test case it’s important to annotate it using <strong>@Test</strong> to tell android that it is a test function.</p><p><strong>line 6- Naming convention </strong>if you noticed the naming convention ,we are using back markers (`test cases allows us to name our functions as such`) , this is not how normal function declaration is done in our regular classes, but we are allowed to do this in test classes,since this is used by the JVM and not referenced by us.</p><p><strong>line 7- RegistrationForm.registerUser()</strong> over here i have accessed the registration class method registerUser and giving it a empty username and valid password which also matches with confirm password.</p><p><strong>assertThat(result).isFalse()</strong>- Finally im telling android that if a similar input has been made by a user in a real app scenario then flag it as false.</p><blockquote><em>Another important thing to note is when you use </em><strong><em>assertThat,</em></strong><em> it by default accesses the assertThat offered by JUnit import, what we need is the assertThat from </em><strong><em>google’s library, so delete the JUnit import and make sure google’s assertThat is used as shown below.</em></strong></blockquote><blockquote>import com.google.common.truth.Truth.assertThat</blockquote><h4>Now that we have written our test case to check for a empty username , we go over to our registration class and create validation for it</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dbb3ee1bb5da975984cab87b57cfe096/href">https://medium.com/media/dbb3ee1bb5da975984cab87b57cfe096/href</a></iframe><p>We return false if username is empty or null , else we return true.</p><p>Now that we have written our first test case and our function validation we run our test case by pressing the green play button in our test class.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/532/1*5dXg9h9byo7iTZNqcHAEuw.png" /><figcaption>press the green button on the left</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xawB9AZChjsMrPbDTEQfmw.png" /></figure><p>After running the test case we are displayed with the result as a pass. Meaning the validation to check if username is empty works.</p><p>Now we can go ahead and finish the remaining test cases to satisfy our rules and complete our validation.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2750bba3e4d376868b9de2edeb3d22b4/href">https://medium.com/media/2750bba3e4d376868b9de2edeb3d22b4/href</a></iframe><p>Registration Util class with all validation satisfying the test cases</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/835b41a4c1336e457410aa3a3164632c/href">https://medium.com/media/835b41a4c1336e457410aa3a3164632c/href</a></iframe><p>And this is the result of our test cases</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aELCjCTIYUJO5rfFtd38BQ.png" /></figure><p>All the test cases has passed meaning our registration validation function is pretty much perfect considering the rules.</p><p>Imagine this scenario , rather than you manually testing your registration activity and spending time, now you can test it all in a single click in less than 10 seconds.</p><p>Now you might argue that i could have written the function before the test cases since i already know what needs to be done which is true, but the point of TDD is making sure you iron out the edge cases first before starting the function implementation</p><p><a href="https://zaidzakir.medium.com/testing-in-android-a-zero-to-hero-tutorial-part-2-577aeb79ae14"><strong>Testing in Android a Zero to Hero Tutorial-Part 2</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b2f3a7a2b6b2" width="1" height="1" alt=""><hr><p><a href="https://medium.com/geekculture/testing-in-android-a-zero-to-hero-tutorial-part-1-b2f3a7a2b6b2">Testing in Android a Zero to Hero Tutorial -Part 1</a> was originally published in <a href="https://medium.com/geekculture">Geek Culture</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Simple Android App using MVVM & Dagger HILT]]></title>
            <link>https://zaidzakir.medium.com/a-simple-android-app-using-mvvm-dagger-hilt-e9f45381f1bc?source=rss-6b774016575------2</link>
            <guid isPermaLink="false">https://medium.com/p/e9f45381f1bc</guid>
            <category><![CDATA[dagger-2]]></category>
            <category><![CDATA[dagger-hilt]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[mvvm]]></category>
            <dc:creator><![CDATA[Zaid Zakir]]></dc:creator>
            <pubDate>Thu, 13 May 2021 06:48:22 GMT</pubDate>
            <atom:updated>2021-05-13T06:48:22.550Z</atom:updated>
            <content:encoded><![CDATA[<p>A article that will explain and help you understand how you can use Dagger HILT in your next project be it big or small 🙌</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*AL52onEK1WzhJkLN" /><figcaption>Photo by <a href="https://unsplash.com/@emmafranceslogan?utm_source=medium&amp;utm_medium=referral">Emma Frances Logan</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h4>What is MVVM?</h4><p>A simple explanation,It is google&#39;s recommended architecture which practices <strong>SEPARATION OF CONCERNS</strong> , what this means is , every layer (Model / View / ViewModel) is independent from each other.</p><p>You should never write all your code in one activity or fragment, to avoid lifecycle related issues. We also do this so that everything is easily testable and readable.</p><p>The parent has direct relation to the child, but the child has no direct relation to the parent.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*-yY0l4XD3kLcZz0rO1sfRA.png" /><figcaption>Image from <a href="https://developer.android.com/">https://developer.android.com/</a></figcaption></figure><p><strong>What is Dagger-HILT?</strong></p><p>If we need to use a method from a different class we usually create objects of that class in the class we need that in, but with DI<strong> </strong>we outsource this work to (in this case) to Dagger HILT . You can think of DI as the middleman in our code who does all the work of creating the preferred object and providing it to the class which needs it.</p><p><strong>Ok let&#39;s get started</strong></p><p>We will be accessing a open source api called <a href="https://github.com/ajzbc/kanye.rest">https://github.com/ajzbc/kanye.rest</a> which will return a new quote of kanye west as a string and display in our activity.</p><p><strong>Full project github repo- </strong><a href="https://github.com/zaidzak9/MediumExample"><strong>https://github.com/zaidzak9/MediumExample</strong></a></p><p><strong>Prerequisites</strong></p><p>A basic understanding of coroutines and liveData/StateFlow will be needed along with this(ignore this if you already do👍)</p><p><strong>My Article on coroutines- </strong><a href="https://zaidzakir.medium.com/coroutines-in-android-explained-8f00a37c8528"><strong>https://zaidzakir.medium.com/coroutines-in-android-explained-8f00a37c8528</strong></a></p><p><strong>Article on liveData &amp; StateFlow-</strong><a href="https://developer.android.com/topic/libraries/architecture/livedata"><strong>https://developer.android.com/topic/libraries/architecture/livedata</strong></a><strong> </strong><a href="https://developer.android.com/kotlin/flow/stateflow-and-sharedflow"><strong>https://developer.android.com/kotlin/flow/stateflow-and-sharedflow</strong></a></p><ol><li><strong>Add these plugins &amp; dependencies in your build.gradle(:app)</strong></li></ol><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/32c170fff98b3f88a6c7f1e494184da3/href">https://medium.com/media/32c170fff98b3f88a6c7f1e494184da3/href</a></iframe><p><strong>2. Add this classpath in your build.gradle(:project) inside dependencies</strong></p><pre>classpath &quot;com.google.dagger:hilt-android-gradle-plugin:2.28.3-alpha&quot;</pre><p><strong>3. Create a MainApplication.class and declare it in your manifest</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/311a9ce8e04b4bcb6a1cc5f36a8308e4/href">https://medium.com/media/311a9ce8e04b4bcb6a1cc5f36a8308e4/href</a></iframe><p><strong>What did we do here? @HiltAndroidApp- </strong>We create a <a href="https://developer.android.com/reference/android/app/Application">application class</a> which hilt uses to setup a lot of its own classes that can use dependency injection,the annotation lets hilt attach itself to the application lifecycle.</p><p><strong>4. Create a AppModule Class</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ecab6fe9c9bd1b2f0fecd318008ac52c/href">https://medium.com/media/ecab6fe9c9bd1b2f0fecd318008ac52c/href</a></iframe><p>First i create a constant val with value of <strong>BASE_URL</strong> that we will be accessing to retrieve the data from , please note that this is not best practice, usually there will be a dedicated class for this, but since this project is created for simplicity of explaining HILT i will declare it here.</p><p><strong>@Module- </strong>denotes that this class are containers for dependencies that has to be injected Example: RetrofitInstance, RoomDBInstance , and also we specify amount of time that this will live in application lifecycle.</p><p><strong>@InstallIn()-</strong> tells dagger how long the scope of the module should live for , Here are some lifecycle scopes for InstallIn()</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GysoMtGF11D7v_OoyFQOEA.png" /><figcaption><a href="https://dagger.dev/hilt/components.html#component-bindings">https://dagger.dev/hilt/components.html#component-bindings</a></figcaption></figure><p>You can figure out the scopes of each of the component through <strong>Created at</strong> and <strong>Destroyed at </strong>columns . Also you have to make sure the component and scope matches each other. <strong>Ex: SingeltonComponent -&gt; @Singleton .</strong></p><p>I used the singleton component and scope so that we are able to use the object of retrofit and provideRepository throughout our app lifecycle.</p><p><strong>@Provides</strong>- denotes to dagger that we will need to provide the following function as injectable dependency to any class which needs it.</p><p><strong>5. Inject your dependencies</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e09444df34c84e8f3f0599c9177e1f72/href">https://medium.com/media/e09444df34c84e8f3f0599c9177e1f72/href</a></iframe><p>Using the <strong>@Inject</strong> annotation we tell dagger HILT to inject object of type KanyeWestApi which contains the retrofit instance in AppModule, so dagger now knows that it has to be injected in this repository class.</p><p>We do the same thing to the viewModel but only difference is we have to use an extra annotation called <strong>@HiltViewModel</strong> , to tell its parent activity the data received from will be a viewmodel.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/93835ed09bbc1aa91112b0cf3178fe11/href">https://medium.com/media/93835ed09bbc1aa91112b0cf3178fe11/href</a></iframe><p><strong>6. Finally Add @AndroidEntryPoint to the activity.</strong></p><pre><strong>@AndroidEntryPoint</strong><br>class MainActivity : AppCompatActivity() { }</pre><p>This Marks the activity to be setup for injection with the standard Hilt Dagger Android components.HILT will create a dependency container that will attach itself to this class lifecycle,Currently this annotation supports activities, fragments, views, services, and broadcast receivers.</p><p><strong>Full project github repo- </strong><a href="https://github.com/zaidzak9/MediumExample"><strong>https://github.com/zaidzak9/MediumExample</strong></a></p><p><strong>Dagger HILT documentation</strong></p><p><a href="https://dagger.dev/hilt/">Hilt</a></p><p>For this simple example these are the functionalities that i have used to incorporate Dagger HILT in the project, but it doesn&#39;t stop here , there are many other annotations which could be used to expand a project .</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e9f45381f1bc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Coroutines in Android explained]]></title>
            <link>https://zaidzakir.medium.com/coroutines-in-android-explained-8f00a37c8528?source=rss-6b774016575------2</link>
            <guid isPermaLink="false">https://medium.com/p/8f00a37c8528</guid>
            <category><![CDATA[kotlin-beginners]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[coroutine]]></category>
            <category><![CDATA[android-app-development]]></category>
            <dc:creator><![CDATA[Zaid Zakir]]></dc:creator>
            <pubDate>Thu, 29 Apr 2021 07:57:51 GMT</pubDate>
            <atom:updated>2021-04-29T07:57:51.702Z</atom:updated>
            <content:encoded><![CDATA[<p>Everything you need to know on coroutines while you wait till your pizza gets delivered.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*tblE1eWonFIZEFUT" /><figcaption>Photo by <a href="https://unsplash.com/@perfectpics2508?utm_source=medium&amp;utm_medium=referral">NIKHIL .</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Implementing coroutines to your android project.</p><pre>// Coroutines<br>implementation &#39;org.jetbrains.kotlinx:kotlinx-coroutines-core:1.4.1&#39;<br>implementation &#39;org.jetbrains.kotlinx:kotlinx-coroutines-android:1.4.1&#39;<br><br>// Coroutine Lifecycle Scopes<br>implementation &quot;androidx.lifecycle:lifecycle-viewmodel-ktx:2.3.1&quot;<br>implementation &quot;androidx.lifecycle:lifecycle-runtime-ktx:2.3.1&quot;</pre><h4><strong>What is coroutines?</strong></h4><p>First you need to know what functions and threads are to make sense of coroutines, <strong>functions</strong> are a set of instructions that give us outputs based on our inputs,<a href="https://developer.android.com/reference/java/lang/Thread"><strong>threads</strong></a> describes in which context these sequence of instructions should be executed in. In android if you don&#39;t manage threading effectively, every code gets executed in the main thread along with UI , this can cause the infamous <a href="https://developer.android.com/training/articles/perf-anr"><strong>ANR crashes/bugs </strong></a><strong>.</strong></p><p>This is where coroutines comes to the rescue</p><ol><li>Coroutines are executed within a <strong>thread</strong> , so many coroutines can be run at a single time without disrupting any other coroutines or the thread in which its running.</li><li>Coroutines are suspendable, meaning any single coroutine can be run,delayed or cancelled at any time.</li><li>And the best part of them is they can change their <a href="https://developer.android.com/reference/android/content/Context">context</a> at any time.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*EjuZl9ozUFYsftmu" /><figcaption>Photo by <a href="https://unsplash.com/@yancymin?utm_source=medium&amp;utm_medium=referral">Yancy Min</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p><strong>Example : Imagine 2 construction sites.</strong></p><p>Site A = Thread 1</p><p>Site B = Thread 2</p><p>Constructions workers = Coroutines doing specific tasks</p><p>Site A-B Architect = You</p><p>breaking it down : In above example any amount of constructions workers(coroutines with tasks) can work in any sites(Threads), If any construction worker is taken out(delayed/cancelled) it will not affect the work of the site, it will carry on as usual, these workers can switch sites(contexts) at any time by the instruction of the architect(you).</p><p>The simplest way to start a coroutine , is in the main function(using GlobalScope not the best practice :P )<br><strong>GlobalScope.<em>launch </em>{your code goes here}</strong></p><p>Coroutines started with Globalscope will live as long as the application lives, meaning it will only end if the app is killed or stopped.Globalscope launches the coroutine in a new thread , you can test this out by printing Thread.currentThread().name inside the launch block and outside in the main function, 2 different names will be printed which indicates 2 different threads.</p><p><strong>Delay</strong></p><pre>GlobalScope.<em>launch </em><strong>{<br>    </strong>delay(1000L)<br><strong>}</strong></pre><p>Delay is <strong>NOT SIMILAR</strong> to sleep function in threads, delay will only pause the coroutine and not the whole thread.</p><p><strong>Suspend Functions</strong></p><pre>suspend fun doNetworkCall()</pre><p>What is it used for ? It is used in situations where any function needs to be delayed or is a long running operation , <strong>ex: a network call</strong> ,these functions can only be invoked by a coroutine or another suspend function</p><p><strong>Coroutine Contexts</strong></p><pre>GlobalScope.<em>launch</em>(Dispatchers.Main) <strong>{<br>    </strong>//used for UI updates<br><strong>}<br></strong>GlobalScope.<em>launch</em>(Dispatchers.IO) <strong>{<br>    </strong>//used for Network calls<br><strong>}<br></strong>GlobalScope.<em>launch</em>(Dispatchers.Default) <strong>{<br>    </strong>//used for long running operations<br><strong>}<br></strong>GlobalScope.<em>launch</em>(Dispatchers.Unconfined) <strong>{<br>    </strong>//used when you don&#39;t want it to be confined to specific thread<br><strong>}<br></strong>GlobalScope.<em>launch</em>(newSingleThreadContext(&quot;myThread&quot;)) <strong>{<br>    </strong>//used when you want it to run on your thread<br><strong>}</strong></pre><p>But the real use of these contexts is to switch between tasks easily, example : in a network call, you can use <strong>Dispatchers.IO</strong> to make the call and switch to <strong>Dispatchers.Main</strong> to update the UI based on the requirements,code example given below.</p><pre>GlobalScope.<em>launch</em>(Dispatchers.IO) <strong>{<br>    </strong>val response  = doNetworkCall()<br>    <strong>withContext(Dispatchers.Main){<br>        yourTextView.text = response</strong><br>    <strong>}<br>}</strong></pre><pre>suspend fun doNetworkCall():String <strong>{</strong><br>    return &quot;response&quot;<br><strong>}</strong></pre><p><strong>Run Blocking</strong></p><pre><strong>runBlocking</strong> {<br>    delay(100L)<br>}</pre><p>runBlocking is used to suspend or delay the entire thread instead of just the coroutine, why would you do this ? Here are few examples</p><ol><li>If your app has some requirement to block the main thread while performing a task in suspend function.</li><li>To do testing with <a href="https://developer.android.com/training/testing/unit-testing/local-unit-tests">JUnit</a> to access suspend function from within a test function</li><li>To maybe just play around with coroutines to see how it works</li></ol><pre>but coroutines started inside the runBlocking will not be       blocked and will run asynchronously with the run blocking and finish at the same time as runBlocking</pre><pre><strong>runBlocking</strong> {<br>    <em>launch</em>(Dispatchers.IO) <strong>{<br>     println(&quot;Task 1&quot;) <br>    }<br>    </strong><em>launch</em>(Dispatchers.IO) <strong>{<br>    println(&quot;Task 2&quot;)</strong><br>    <strong>}<br></strong>}</pre><p><strong>Jobs,Waiting and Cancellation</strong></p><p>When you launch a coroutine it will return a job, you can assign this to a val , you can then attach another coroutine to the first job and this will allow you to continue tasks sequentially as per your needs, you can delay or cancel it. Below example i am attaching val job to a coroutine and joining it with runBlocking, what this will do is block the thread until the first coroutine is complete and join in from there.</p><pre>val job = GlobalScope.<em>launch</em>(Dispatchers.Default) <strong>{<br>    </strong><em>repeat</em>(2)<strong>{<br>        </strong>Log.d(TAG,&quot;Job coroutine running now&quot;)<br>    <strong>}<br>}<br></strong>runBlocking<em> </em><strong>{<br>    </strong>job.join()<br>    Log.d(TAG,&quot;2ND coroutine running now&quot;)<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/548/1*5MgPgcnqj17JjaeDqghcCw.png" /><figcaption>(logcat)2nd coroutine launches immediately after the 1st.</figcaption></figure><p><strong>.cancel()</strong> method keyword has the ability to cancel a operation , but .<strong>cancel()</strong> is a <strong>co-operative</strong> function which means our coroutines needs to be setup correctly to cancel ,that is why in below example i used delay() since it’s a small task to begin with, you can use delay() and runBlocking{} to your purpose.</p><pre>val job = GlobalScope.<em>launch</em>(Dispatchers.Default) <strong>{<br>    </strong><em>repeat</em>(5)<strong>{<br>        </strong>Log.d(TAG,&quot;Job coroutine running now&quot;)<br>        delay(1000L)<br>    <strong>}<br>}<br></strong>val job2 = GlobalScope.<em>launch </em><strong>{<br>    </strong>delay(2000L)<br>    job.cancel()<br>    Log.d(TAG,&quot;Job coroutine is cancelled, Job2 is running now&quot;)<br><strong>}</strong></pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/816/1*5rGOsWhKdaJX4GlZUOmvHQ.png" /><figcaption>(logcat)Job2 cancels job which is supposed to print 5 times.</figcaption></figure><p>but then you might wonder , then why do we even need this function?</p><p>Coroutines are usually busy running their tasks , so .cancel() on its own won&#39;t cancel that particular coroutine, thats where you should you should use the keyword isActive (boolean), which will check the status before running if its been cancelled or not. Example below</p><pre>GlobalScope.<em>launch</em>(Dispatchers.Default) <strong>{<br>    </strong><em>repeat</em>(5)<strong>{<br>        if (<em>isActive</em>)</strong> {<br>            Log.d(TAG, &quot;Job coroutine running now&quot;)<br>}<strong>}}</strong></pre><p><strong>Async and Await</strong></p><p>If we have several suspend functions and execute them in a coroutine they are sequential by default, the first function will be executed initially and when its finished the second one will be executed, however when we do network calls we sometimes need them to run concurrently(at the same time).</p><p>There are 2 ways to do this</p><pre><strong>Solution 1 (The bad practice)</strong></pre><pre>GlobalScope.<em>launch</em>(Dispatchers.IO) <strong>{<br>    </strong>val job1 = <strong><em>launch</em></strong><em> </em><strong>{ </strong>networkCall1 <strong>}<br>    </strong>val job2 = <strong><em>launch</em></strong><em> </em><strong>{ </strong>networkCall2 <strong>}<br>    </strong>job1.join()<br>    job2.join()<br>    Log.d(TAG,&quot;Print response : $job1 and $job2&quot;)<br>    <strong>}</strong></pre><pre><strong>Why is this bad practice?<br></strong>launch is used to execute and forget , if the code inside the launch stops with a execution or error, it is treated as an unhandled/uncaught exception in a thread, and join waits for its completion but does not take responsibility which might result in a crash or ANR.</pre><pre><strong>Solution 2(The good practice)</strong></pre><pre>GlobalScope.<em>launch</em>(Dispatchers.IO) <strong>{<br>    </strong>val job1 = <strong><em>async</em></strong><em> </em><strong>{ </strong>networkCall1 <strong>}<br>    </strong>val job2 = <strong><em>async</em></strong><em> </em><strong>{ </strong>networkCall2 <strong>}<br>    </strong>job1.join()<br>    job2.join()<br>    Log.d(TAG,&quot;Print response : $job1<strong>.await()</strong> and $job2<strong>.await()</strong>&quot;)<br>    <strong>}</strong></pre><pre><strong>Why is this good practice?<br>async</strong> and <strong>await</strong> takes responsibility of the task they run and respond accordingly to the final result,they are a instance of the <a href="https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/-deferred/index.html">deferred</a>,the result of the function can be retrieved by the await method,no exceptions will be ignored and can be handled using the <a href="https://kotlin.github.io/kotlinx.coroutines/kotlinx-coroutines-core/kotlinx.coroutines/-deferred/get-completion-exception-or-null.html">getCompletionExceptionOrNull</a>.</pre><p><strong>LifecycleScope and ViewModelScope</strong></p><p>To implement these you need to add 2 extra dependencies which are already mentioned above.</p><p>Earlier i had mentioned GlobalScope as a bad practice because it will keep running regardless of the activity lifecycle that it was initiated in, this creates a lot of memory leaks because GlobalScope will stop only when the application is destroyed. If the Activity which provides resources used to create the GlobalScope is destroyed , it won&#39;t be garbage collected because the resources are still being used.</p><pre><em>To prevent the above mentioned horror show we use </em><strong><em>lifecycleScope</em></strong><em>, this will run the coroutine in accordance to the activities lifecycle.</em></pre><pre><strong><em>lifecycleScope</em></strong>.<em>launch </em><strong>{<br>    </strong>doSomething()<br>    <strong>}</strong></pre><pre>Another useful scope is the <strong>viewModelScope</strong>, this does the same function as mentioned above only difference is it will run according to the viewmodel lifecycle, viewmodels are used in <a href="https://developer.android.com/jetpack/guide#recommended-app-arch">MVVM architecture</a> recommended by google.</pre><pre><strong>viewModelScope</strong>.<em>launch </em><strong>{<br>    </strong>doSomething()<br>    <strong>}</strong></pre><p><strong>Coroutines with Retrofit</strong></p><p>The usual way of making retrofit calls is done using the enqueue function and result is returned through the callback method, but enqueue creates a whole new thread and this isn&#39;t efficient. We can instead execute this inside a coroutine.</p><pre>interface MyAPI{<br>    @GET(&quot;url&quot;)<br>    suspend fun getApi():Response&lt;YourModelClass&gt;<br>}</pre><pre>MainActivity {<br><em>lifecycleScope</em>.<em>launch </em><strong>{ <br>    </strong>val response = api.getApi()<br>    if (response.<em>isSuccessful</em>){<br>        //do something here<br>    }<br><strong>}</strong>}</pre><pre>This is just a simple example to show how much less code it is to call an api through coroutines and its not needed to start a thread for it.</pre><p>I hope this article helped you understand coroutines and this was enough to get you started, in the meantime enjoy your pizza.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8f00a37c8528" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[OOP concepts with Kotlin (Android)]]></title>
            <link>https://zaidzakir.medium.com/oop-concepts-with-kotlin-android-12ed06bcc6b2?source=rss-6b774016575------2</link>
            <guid isPermaLink="false">https://medium.com/p/12ed06bcc6b2</guid>
            <category><![CDATA[google]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[oop-concepts]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Zaid Zakir]]></dc:creator>
            <pubDate>Mon, 19 Apr 2021 07:49:01 GMT</pubDate>
            <atom:updated>2021-04-19T07:49:01.629Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Q86GqYLWjP8AULRn" /><figcaption>Photo by <a href="https://unsplash.com/@2mduffel?utm_source=medium&amp;utm_medium=referral">Mark Duffel</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>This article mainly focuses on how OOP theory can be applied on android using Google’s latest language , <a href="https://kotlinlang.org/docs/getting-started.html"><strong>Kotlin</strong></a>!</p><p>The 4 main concepts in OOP are <strong>Inheritance</strong>,<strong>Abstraction,Polymorphism</strong> and <strong>Encapsulation, </strong>The most fundamental reasoning behind using OOP concepts in projects is to allow developers to scale, test and manage their projects efficiently.</p><h4><strong>Inheritance</strong></h4><p>All classes in your project which have no defined superclass, inherit from a common superclass called <a href="https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-any/"><strong>any</strong></a> in kotlin, to make a class inheritable you have to use the keyword <strong>open</strong>, because by default a class is final and cannot be inheritable. A simple example below, we have a class parent which has a inheritable function called <strong>eyeColor, </strong>and we have the child class which is able to access that function.</p><pre><strong>open</strong> class Parent {<br>fun eyeColor(colorName:String) = <br><em>println</em>(&quot;My child&#39;s eye color is $colorName&quot;)<br>}</pre><pre>==========================================================<br>//to inherit a class you type colon(:) and the name of parent class<br>class Child <strong>: Parent ()</strong>{<br>    init {<br>        eyeColor(&quot;Blue&quot;)<br>    }<br>}</pre><h4>Abstraction</h4><p>This class holds the definitions of functions needed by all the subclasses which are inheriting from it,abstract classes do not need to know the implementations,you can make a class abstract by using the the keyword abstract , abstract classes cannot be instantiated (object cannot be created).</p><pre><strong>fun main()</strong> {<br>    val circle = Circle(5.0)<br>    circle.shapeName(&quot;Circle&quot;)</pre><pre>    val triangle = Triangle(2.0,3.0,4.0)<br>    triangle.shapeName(&quot;Triangle&quot;)<br>}<br>===================================================================<br><strong>abstract class Shape</strong>{<br>    abstract fun area() : Double<br>    abstract fun perimeter() : Double<br>    fun shapeName(name:String){<br>        <em>println</em>(&quot;The name of shape is $name&quot;)<br>    }<br>}<br>===================================================================<br><strong>class Circle (var radius : Double): Shape()</strong>{<br>    private val pi = 3.14<br>    init {<br>        <em>println</em>(&quot;The area of circle is ${area()}&quot;)<br>        <em>println</em>(&quot;The perimeter of circle is ${perimeter()}&quot;)<br>    }<br>    override fun area() = radius * radius * pi<br>    override fun perimeter() = 2 * radius * pi<br>}<br>===================================================================<br><strong>class Triangle (var a : Double, var b : Double,var c : Double): Shape ()</strong>{<br>    init {<br>        <em>println</em>(&quot;The area of Triangle is ${area()}&quot;)<br>        <em>println</em>(&quot;The perimeter of perimeter is ${perimeter()}&quot;)<br>    }<br>    override fun area(): Double = <em>sqrt</em>((perimeter() / 2) * (perimeter() / 2 - a) * (perimeter() / 2 - b) * (perimeter() / 2 - c))<br>    override fun perimeter() = a + b + c<br>}</pre><p>In the code above , circle and triangle class is instantiated in the main class and a name is passed as a parameter and inside the init block of these classes the methods is where the logic/implementation is handled. The shape class only has the definitions of the methods needed by any classes that inherits it.</p><h4><strong>Encapsulations</strong></h4><p>is a term used to describe the scope visibility of variables and functions in classes, there are 4 main types of <a href="https://kotlinlang.org/docs/visibility-modifiers.html">visibility modifiers</a></p><p><strong>Public</strong> , by default all classes and variables are public , which means they are accessible for the entire project.</p><p><strong>Private</strong>, variables and functions which are private can be accessed only within the class they are declared in.</p><p><strong>Protected</strong> , these variables and functions can be accessed within the class and all classes which inherit this class</p><p><a href="https://kotlinlang.org/docs/visibility-modifiers.html#modules"><strong>Internal</strong></a><strong>, </strong>internal allows visibility in the same module.</p><h4><strong>Polymorphism</strong></h4><p>Which means “occurring in several different forms”, can be demonstrated by overriding and overloading functions or variables.</p><p><strong>Overriding</strong> the process of re-declaring existing variables or functions in superclass for different implementations. to override a particular variable or function it must be declared using the open keyword in the superclass and then the keyword override should be used in the child class which overrides it.</p><pre><strong>open</strong> class Car {<br><strong>open</strong> val speed:String = &quot;Average speed 200Kmph&quot;</pre><pre>}</pre><pre>==========================================================</pre><pre>class Bmw : Car (){<br>//you can override a val with var but not vice versa<strong><br>override</strong> val speed = &quot;Bmw speed 250Kmph&quot;<br>}</pre><p><strong>overloading </strong>is done when you want create functions with similar functionality and name but also want the compiler to be able to distinguish each functions uniquely,you can overload a function by have different parameter types or different amount of parameters, overloading can also be seen through out your kotlin projects example such as the inbuilt println() function which can take any parameter.</p><pre>fun main() {<br> <em>println</em>(&quot;This is 1st methods max 1 : ${<em>getMax</em>(2, 3)}&quot;)<br> <em>println</em>(&quot;This is 1st methods max 3 : ${<em>getMax</em>(6.4, 3)}&quot;)<br> <em>println</em>(&quot;This is 1st methods max 2 : ${<em>getMax</em>(2.4, 3.4)}&quot;)<br> <em>println</em>(&quot;This is 1st methods max 4: ${<em>getMax</em>(4, 3 , &quot;4th get max&quot;)}&quot;)<br>}<br>//1<br>fun getMax(a: Int, b: Int) = if (a &gt; b) a else b<br>//2<br>fun getMax(a: Double, b: Double) = if (a &gt; b) a else b<br>//3<br>fun getMax(a: Double, b: Int) = if (a &gt; b) a else b<br>//4<br>fun getMax(a: Int, b: Int, c:String) = if (a &gt; b) a else c</pre><p>This article was an overview of these basic concepts in kotlin , you can check out the kotlin documentation for more information :</p><p><a href="https://kotlinlang.org/docs/home.html">Kotlin Docs | Kotlin</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=12ed06bcc6b2" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>