<?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"><channel><title><![CDATA[Tej Pratap Singh]]></title><description><![CDATA[Code Stories]]></description><link>https://blog.tejpratapsingh.com</link><image><url>https://cdn.hashnode.com/res/hashnode/image/upload/v1572529751998/FGXShDj5a.png</url><title>Tej Pratap Singh</title><link>https://blog.tejpratapsingh.com</link></image><generator>RSS for Node</generator><lastBuildDate>Sat, 06 Jun 2026 17:36:01 GMT</lastBuildDate><atom:link href="https://blog.tejpratapsingh.com/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[How to create a lifecycle aware custom class in Android.]]></title><description><![CDATA[We all know, each component in Android has its lifecycle, be it Activity, Fragment or Service. Each component gets created and destroys (and a few other stages in between).
To create a custom class that is lifecycle aware inherently, we can use a set...]]></description><link>https://blog.tejpratapsingh.com/how-to-create-a-lifecycle-aware-custom-class-in-android</link><guid isPermaLink="true">https://blog.tejpratapsingh.com/how-to-create-a-lifecycle-aware-custom-class-in-android</guid><category><![CDATA[Android]]></category><category><![CDATA[android app development]]></category><dc:creator><![CDATA[Tej Pratap Singh]]></dc:creator><pubDate>Thu, 17 Aug 2023 10:39:51 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/Z9fW8Nn7D24/upload/c76e1ac7da511fd31f87a85d7d508ebc.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>We all know, each component in Android has its lifecycle, be it Activity, Fragment or Service. Each component gets created and destroys (and a few other stages in between).</p>
<p>To create a custom class that is lifecycle aware inherently, we can use a set of libraries provided under <a target="_blank" href="https://developer.android.com/jetpack/androidx/releases/lifecycle">jetpack lifecycle</a>.</p>
<p>For example, I want to create a timer, which invokes a method on each interval, and also, it should be lifecycle aware so it dies with its owner.</p>
<p>Firstly, we will create an interface that extends <code>LifecycleOwner</code>, this interface is implemented all new <code>androidx.</code> components.</p>
<pre><code class="lang-java"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">interface</span> <span class="hljs-title">OnIntervalListener</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">LifecycleOwner</span> </span>{
    <span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">onTimerInterval</span><span class="hljs-params">()</span></span>;
}
</code></pre>
<p>Now, we create out actual timer,</p>
<pre><code class="lang-java"><span class="hljs-comment">/**
 * <span class="hljs-doctag">@implNote</span> An implementation of lifecycle aware timer, can be attached to Activity or fragment
 */</span>
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">LifecycleAwareTimer</span> <span class="hljs-keyword">implements</span> <span class="hljs-title">Runnable</span>, <span class="hljs-title">DefaultLifecycleObserver</span> </span>{

    <span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">interface</span> <span class="hljs-title">OnIntervalListener</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">LifecycleOwner</span> </span>{
        <span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">onTimerInterval</span><span class="hljs-params">()</span></span>;
    }

    <span class="hljs-keyword">private</span> <span class="hljs-keyword">final</span> Handler mHandler = <span class="hljs-keyword">new</span> Handler(Looper.getMainLooper());

    <span class="hljs-keyword">private</span> <span class="hljs-keyword">final</span> <span class="hljs-keyword">long</span> mInterval;

    <span class="hljs-keyword">private</span> <span class="hljs-keyword">final</span> OnIntervalListener mOnIntervalListener;

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">LifecycleAwareTimer</span><span class="hljs-params">(<span class="hljs-keyword">long</span> interval, <span class="hljs-meta">@NonNull</span> OnIntervalListener onIntervalListener)</span> </span>{
        mInterval = interval;
        mOnIntervalListener = onIntervalListener;

        mOnIntervalListener.getLifecycle().addObserver(<span class="hljs-keyword">this</span>);
    }

    <span class="hljs-meta">@Override</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">run</span><span class="hljs-params">()</span> </span>{
        mOnIntervalListener.onTimerInterval();
    }

    <span class="hljs-meta">@Override</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">onResume</span><span class="hljs-params">(<span class="hljs-meta">@NonNull</span> LifecycleOwner owner)</span> </span>{
        mHandler.removeCallbacksAndMessages(<span class="hljs-keyword">null</span>);
        mHandler.postDelayed(<span class="hljs-keyword">this</span>, mInterval);
    }

    <span class="hljs-meta">@Override</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">onPause</span><span class="hljs-params">(<span class="hljs-meta">@NonNull</span> LifecycleOwner owner)</span> </span>{
        mHandler.removeCallbacksAndMessages(<span class="hljs-keyword">null</span>);
    }

    <span class="hljs-meta">@Override</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">onDestroy</span><span class="hljs-params">(<span class="hljs-meta">@NonNull</span> LifecycleOwner owner)</span> </span>{
        mHandler.removeCallbacksAndMessages(<span class="hljs-keyword">null</span>);
        mOnIntervalListener.getLifecycle().removeObserver(<span class="hljs-keyword">this</span>);
    }
}
</code></pre>
<p>Now, you can use it creates a new instance from Activity or Fragment and it will die once its owner dies.</p>
]]></content:encoded></item><item><title><![CDATA[AIDL : IPC, The Android way]]></title><description><![CDATA[The Android Interface Definition Language (AIDL) is similar to other IDLs: it lets you define the programming interface that both the client and service agree upon in order to communicate with each other using interprocess communication (IPC).

Aidl ...]]></description><link>https://blog.tejpratapsingh.com/aidl-ipc-the-android-way</link><guid isPermaLink="true">https://blog.tejpratapsingh.com/aidl-ipc-the-android-way</guid><category><![CDATA[Android]]></category><category><![CDATA[RPC]]></category><category><![CDATA[RPC framework]]></category><category><![CDATA[AIDL]]></category><dc:creator><![CDATA[Tej Pratap Singh]]></dc:creator><pubDate>Sun, 04 Jun 2023 13:51:34 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1685887032744/adbfd0dc-1df0-4716-960a-552915105d11.avif" length="0" type="image/jpeg"/><content:encoded><![CDATA[<blockquote>
<p>The Android Interface Definition Language (AIDL) is similar to other <a target="_blank" href="https://en.wikipedia.org/wiki/Interface_description_language">IDLs</a>: it lets you define the programming interface that both the client and service agree upon in order to communicate with each other using interprocess communication (IPC).</p>
</blockquote>
<p>Aidl consists of 3 parts:</p>
<ol>
<li><p>AIDL file</p>
</li>
<li><p>Client application</p>
</li>
<li><p>Server application</p>
</li>
</ol>
<h3 id="heading-creating-aidl-file">Creating AIDL file</h3>
<ol>
<li><p>Enable build feature in your <code>build.gradle</code>.</p>
<pre><code class="lang-java"> buildFeatures {
     aidl = <span class="hljs-keyword">true</span>
 }
</code></pre>
</li>
<li><p>Create a new AIDL file using <code>File</code> -&gt; <code>New</code> -&gt; <code>AIDL</code> -&gt; <code>AIDL File</code></p>
</li>
<li><p>Let's name it <code>ICalculator.aidl</code></p>
</li>
<li><p>Declare aidl methods:</p>
<pre><code class="lang-kotlin"> <span class="hljs-class"><span class="hljs-keyword">interface</span> <span class="hljs-title">IExampleAidlInterface</span> </span>{
     int add(int a, int b);
 }
</code></pre>
</li>
</ol>
<h3 id="heading-create-an-aidl-server">Create an AIDL server</h3>
<p>An AIDL server is an app that does the actual work and sends back the result to requesting clients. One service can connect with multiple clients via Binders.</p>
<p>Steps:</p>
<ol>
<li><p>Create a service, e.g. <code>CalculatorService extends Service</code></p>
</li>
<li><p>Create an Implementation of <code>ICalculator.Stub</code>, lets name it <code>CalculatorImpl</code></p>
</li>
<li><p>Implement methods:</p>
<pre><code class="lang-kotlin"> <span class="hljs-keyword">object</span> CalculatorImpl : ICalculator.Stub() {
     <span class="hljs-keyword">override</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">add</span><span class="hljs-params">(a: <span class="hljs-type">Int</span>, b: <span class="hljs-type">Int</span>)</span></span>: <span class="hljs-built_in">Int</span> {
         <span class="hljs-keyword">return</span> a + b
     }
 }
</code></pre>
</li>
<li><p>Expose your stub implementation with a service binder:</p>
<pre><code class="lang-kotlin"> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">CalculatorService</span> : <span class="hljs-type">Service</span></span>() {
     <span class="hljs-keyword">override</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">onBind</span><span class="hljs-params">(intent: <span class="hljs-type">Intent</span>)</span></span>: IBinder {
         <span class="hljs-keyword">return</span> CalculatorImpl
     }
 }
</code></pre>
</li>
</ol>
<p>Now your service is ready to be consumed by your clients, now let's create a client application.</p>
<h3 id="heading-create-an-aidl-client">Create an AIDL client</h3>
<p>An AIDL client is an app that binds to an AIDL service, calls API, and shows a response inside its views.</p>
<p>Steps:</p>
<ol>
<li><p>Create a service connection:</p>
<pre><code class="lang-kotlin"> <span class="hljs-keyword">private</span> <span class="hljs-keyword">var</span> aidlService: ICalculator? = <span class="hljs-literal">null</span>
 <span class="hljs-keyword">private</span> <span class="hljs-keyword">val</span> serviceConnection = <span class="hljs-keyword">object</span> : ServiceConnection {
     <span class="hljs-keyword">override</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">onServiceConnected</span><span class="hljs-params">(name: <span class="hljs-type">ComponentName</span>?, service: <span class="hljs-type">IBinder</span>?)</span></span> {
         aidlService = ICalculator.Stub.asInterface(service)
         Toast.makeText(applicationContext, <span class="hljs-string">"Service Connected"</span>, Toast.LENGTH_LONG).show()
     }

     <span class="hljs-keyword">override</span> <span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">onServiceDisconnected</span><span class="hljs-params">(name: <span class="hljs-type">ComponentName</span>?)</span></span> {
         aidlService = <span class="hljs-literal">null</span>
         Toast.makeText(applicationContext, <span class="hljs-string">"Service Disconnected"</span>, Toast.LENGTH_LONG).show()
     }
 }
</code></pre>
</li>
<li><p>Connect to AIDL service via Binders.</p>
<pre><code class="lang-kotlin"> <span class="hljs-keyword">val</span> serviceIntent = Intent()
 serviceIntent.component = ComponentName(BuildConfig.AIDL_PACKAGE, BuildConfig.AIDL_SERVICE)
 bindService(serviceIntent, serviceConnection, BIND_AUTO_CREATE)
</code></pre>
</li>
<li><p>Call methods of AIDL after successful connection:</p>
<pre><code class="lang-kotlin"> aidlService?.add(<span class="hljs-number">2</span>, <span class="hljs-number">2</span>)?.let {
     Toast.makeText(
         applicationContext,
         String.format(Locale.getDefault(), <span class="hljs-string">"Sum is: %d"</span>, it),
         Toast.LENGTH_LONG
     ).show()
 }
</code></pre>
</li>
</ol>
<h2 id="heading-limitations">Limitations</h2>
<p>There is one BIG gotcha with AIDL services, which is when the system is in doze mode, your service app might not start to respond to requests.</p>
<hr />
<p>Here is an example application using AIDL in real life 😎</p>
<div class="embed-wrapper"><div class="embed-loading"><div class="loadingRow"></div><div class="loadingRow"></div></div><a class="embed-card" href="https://github.com/tejpratap46/AIDL-Example">https://github.com/tejpratap46/AIDL-Example</a></div>
]]></content:encoded></item><item><title><![CDATA[How to use Bitwise while setting properties]]></title><description><![CDATA[Sometimes we are faced with a situation, where a parameter can have multiple values, or even it can have combination of those values.
We have a few choices here, either we create multiple fields for each property, which is hard to scale but easier to...]]></description><link>https://blog.tejpratapsingh.com/how-to-use-bitwise-while-setting-properties</link><guid isPermaLink="true">https://blog.tejpratapsingh.com/how-to-use-bitwise-while-setting-properties</guid><category><![CDATA[Programming Blogs]]></category><category><![CDATA[Kotlin]]></category><category><![CDATA[bitwise]]></category><dc:creator><![CDATA[Tej Pratap Singh]]></dc:creator><pubDate>Tue, 02 May 2023 11:24:22 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1683026543755/6db2ae9a-dc64-4d52-859a-7f86a6b6957f.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Sometimes we are faced with a situation, where a parameter can have multiple values, or even it can have combination of those values.</p>
<p>We have a few choices here, either we create multiple fields for each property, which is hard to scale but easier to understand.</p>
<p>Here is a code sample for that:</p>
<pre><code class="lang-kotlin"><span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">main</span><span class="hljs-params">()</span></span> {
    order(<span class="hljs-literal">true</span>, <span class="hljs-literal">true</span>, <span class="hljs-literal">false</span>)
}

<span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">order</span><span class="hljs-params">(hasOrderedCheeseBurger: <span class="hljs-type">Boolean</span>, hasOrderedFries: <span class="hljs-type">Boolean</span>, hasOrderedSoda: <span class="hljs-type">Boolean</span>)</span></span> {
    println(<span class="hljs-string">"Has Ordered CHEESEBURGER : <span class="hljs-subst">${hasOrderedCheeseBurger}</span>"</span>); <span class="hljs-comment">// true</span>
    println(<span class="hljs-string">"Has Ordered FRIES : <span class="hljs-subst">${hasOrderedFries}</span>"</span>); <span class="hljs-comment">// true</span>
    println(<span class="hljs-string">"Has Ordered SODA : <span class="hljs-subst">${hasOrderedSoda}</span>"</span>); <span class="hljs-comment">// false</span>
}
</code></pre>
<p>As you can see, we had to send 3 different parameters to know what this user had ordered and imagine, if, in future we need to add another item, let's say <code>SANDWICH</code> then we need to add another parameter.</p>
<hr />
<p>Now, instead of passing multiple parameters, we can use bit manipulation to combine multiple parameters into a single parameter.</p>
<pre><code class="lang-kotlin"><span class="hljs-keyword">val</span> CHEESEBURGER = <span class="hljs-number">2</span>; <span class="hljs-comment">// 00000010</span>
<span class="hljs-keyword">val</span> FRIES = <span class="hljs-number">4</span>;        <span class="hljs-comment">// 00000100</span>
<span class="hljs-keyword">val</span> SODA = <span class="hljs-number">8</span>;         <span class="hljs-comment">// 00001000</span>

<span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">main</span><span class="hljs-params">()</span></span> {
    <span class="hljs-keyword">val</span> ordered = CHEESEBURGER or FRIES;

    order(ordered)
}

<span class="hljs-function"><span class="hljs-keyword">fun</span> <span class="hljs-title">order</span><span class="hljs-params">(what: <span class="hljs-type">Int</span>)</span></span> {
    <span class="hljs-keyword">val</span> hasOrderedCheeseBurger = what and CHEESEBURGER == CHEESEBURGER;
    <span class="hljs-keyword">val</span> hasOrderedFries = what and FRIES == FRIES;
    <span class="hljs-keyword">val</span> hasOrderedSoda = what and SODA == SODA;
    println(<span class="hljs-string">"Has Ordered CHEESEBURGER : <span class="hljs-subst">${hasOrderedCheeseBurger}</span>"</span>); <span class="hljs-comment">// true</span>
    println(<span class="hljs-string">"Has Ordered FRIES : <span class="hljs-subst">${hasOrderedFries}</span>"</span>); <span class="hljs-comment">// true</span>
    println(<span class="hljs-string">"Has Ordered SODA : <span class="hljs-subst">${hasOrderedSoda}</span>"</span>); <span class="hljs-comment">// false</span>
}
</code></pre>
<p>Here, bitwise allows us to add as many values as we need into a single parameter.</p>
]]></content:encoded></item><item><title><![CDATA[Limitation of PowerMockito.whenNew()]]></title><description><![CDATA[Powemock is a very powerful tool in any Java Developer's arsenal, it allows a developer to change his code at the bytecode level. This is especially beneficial when we want to modify some functionality of source (System Under Test).
Whey we need when...]]></description><link>https://blog.tejpratapsingh.com/limitation-of-powermockitowhennew</link><guid isPermaLink="true">https://blog.tejpratapsingh.com/limitation-of-powermockitowhennew</guid><category><![CDATA[Android]]></category><category><![CDATA[Testing]]></category><category><![CDATA[PowerMock]]></category><category><![CDATA[Java]]></category><dc:creator><![CDATA[Tej Pratap Singh]]></dc:creator><pubDate>Tue, 07 Feb 2023 10:25:05 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/lzh3hPtJz9c/upload/175f654fbf0e2c64cd83537b23cad9ac.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Powemock is a very powerful tool in any Java Developer's arsenal, it allows a developer to change his code at the bytecode level. This is especially beneficial when we want to modify some functionality of source (System Under Test).</p>
<h3 id="heading-whey-we-need-whennew">Whey we need <code>whenNew()</code> ?</h3>
<p><code>whenNew()</code> allows us to inject our <code>fake</code> or <code>mock</code> instead of actually creating a new object of said class.</p>
<p>This works great, we just need to add our class in <code>@PrepareForTest</code> annotation and PowerMock will inject our mock. Just like that.</p>
<p>Here is an example class:</p>
<pre><code class="lang-java"><span class="hljs-comment">// Example Source Class</span>
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">ExampleClass</span> </span>{
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">int</span> <span class="hljs-title">getHeight</span><span class="hljs-params">()</span> </span>{
        <span class="hljs-comment">// Lets say we have a generic method which provides different result base on the provided id</span>
        <span class="hljs-keyword">final</span> CustomClass customClassInstance = <span class="hljs-keyword">new</span> CustomClass();
        <span class="hljs-keyword">return</span> customClass.getHeight();
    }
}
</code></pre>
<p>and here is a test case using <code>whenNew()</code> injection.</p>
<pre><code class="lang-java"><span class="hljs-meta">@RunWith(PowerMockRunner.class)</span>
<span class="hljs-meta">@PrepareForTest({
    ExampleClass.class
})</span>
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">ExampleClassTest</span> </span>{

    <span class="hljs-keyword">private</span> ExampleClass classUnderTest;

    <span class="hljs-meta">@Before</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">setUp</span><span class="hljs-params">()</span> <span class="hljs-keyword">throws</span> Exception </span>{
        <span class="hljs-comment">// Create constructor of ExampleClass</span>
        classUnderTest = <span class="hljs-keyword">new</span> ExampleClass();
    }

    <span class="hljs-meta">@Test</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">getHeight_shoudReturnHeightOfView</span><span class="hljs-params">()</span> <span class="hljs-keyword">throws</span> NoSuchMethodException </span>{
        <span class="hljs-keyword">final</span> <span class="hljs-keyword">int</span> expectedHeight = <span class="hljs-number">100</span>;
        <span class="hljs-comment">// Given</span>
        <span class="hljs-keyword">final</span> CustomClass mckCustomClass = Mockito.mock(CustomClass.class);
        Mockito.when(mckCustomClass.getHeight()).theReturn(expectedHeight);
        // <span class="hljs-function">Make sure you match exact parameters <span class="hljs-keyword">while</span> <span class="hljs-title">mocking</span> <span class="hljs-params">(same as we <span class="hljs-keyword">do</span> <span class="hljs-keyword">for</span> Mockito.mock statements)</span>.
        <span class="hljs-comment">// There is also withArguments(first, second, ....)</span>
        <span class="hljs-comment">// and withAnyArguments() for cases when you don't care for arguments passed.</span>
        PowerMockito.<span class="hljs-title">whenNew</span><span class="hljs-params">(CustomClass.class)</span>.<span class="hljs-title">withNoArguments</span><span class="hljs-params">()</span>.<span class="hljs-title">thenReturn</span><span class="hljs-params">(mckCustomClass)</span></span>;

        <span class="hljs-keyword">final</span> <span class="hljs-keyword">int</span> actualResult = classUnderTest.getHeight();

        Assert.assertEquals(expectedHeight, actualResult);
    }
}
</code></pre>
<h3 id="heading-now-lets-come-to-the-problem">Now let's come to the problem...</h3>
<p>Let's say you have the following class to test:</p>
<pre><code class="lang-java"><span class="hljs-comment">// ClassToTest</span>
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">ClassToTest</span> </span>{
    <span class="hljs-comment">// heavy method</span>
    <span class="hljs-function"><span class="hljs-keyword">private</span> <span class="hljs-keyword">void</span> <span class="hljs-title">doInBackground</span><span class="hljs-params">()</span> </span>{
        <span class="hljs-keyword">new</span> Thread() {
            <span class="hljs-meta">@Override</span>
            <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">run</span><span class="hljs-params">()</span> </span>{
                <span class="hljs-keyword">final</span> CustomClass customClassInstance = <span class="hljs-keyword">new</span> CustomClass();
                <span class="hljs-keyword">int</span> height = customClass.getHeight();
                <span class="hljs-comment">// ... some heavey operation on height</span>
            }
        }.start();
    }
}
</code></pre>
<p>Now, in the above example, a new instance of <code>CustomClass</code> is created inside a nested scope (<code>Thread</code>), hence modifying bytecode of <code>ClassToTest</code> will no longer work as <code>new CustomClass()</code> is not inside its scope.</p>
<h3 id="heading-what-to-do">What to do?</h3>
<p>Powermock has other tools to deal with such situations, firstly, you need to add <code>CustomClass</code> in <code>@PrepareForTest()</code> and <code>suppress()</code> constructors and <code>stub()</code> <code>getHeight()</code> method to modify its behaviour according to your test requirements.</p>
<p>Here is example code:</p>
<pre><code class="lang-java"><span class="hljs-meta">@RunWith(PowerMockRunner.class)</span>
<span class="hljs-meta">@PrepareForTest({
    ExampleClass.class,
    CustomClass.class
})</span>
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">ExampleClassTest</span> </span>{

    <span class="hljs-keyword">private</span> ExampleClass classUnderTest;

    <span class="hljs-meta">@Before</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">setUp</span><span class="hljs-params">()</span> <span class="hljs-keyword">throws</span> Exception </span>{
        <span class="hljs-comment">// Create constructor of ExampleClass</span>
        classUnderTest = <span class="hljs-keyword">new</span> ExampleClass();
    }

    <span class="hljs-meta">@Test</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">getHeight_shoudReturnHeightOfView</span><span class="hljs-params">()</span> <span class="hljs-keyword">throws</span> NoSuchMethodException </span>{
        <span class="hljs-keyword">final</span> <span class="hljs-keyword">int</span> expectedHeight = <span class="hljs-number">100</span>;
        <span class="hljs-comment">// Given</span>
        PowerMockito.suppress(CustomClass.class.getConstructors());
        PowerMockito.stub(CustomClass.class.getMethod(<span class="hljs-string">"getHeight"</span>)).toReturn(expectedHeight);
        <span class="hljs-comment">// ...</span>
    }
}
</code></pre>
<p>P.S. PowerMock has <code>suppress()</code> , <code>sub()</code> and <code>replace()</code> methods to modify individual elements of any class. Please read more about methods declared in <code>PowerMockito</code> class and see if you find an alternate solution to your use case.</p>
]]></content:encoded></item><item><title><![CDATA[Android: How to create Custom Calendar with RecyclerView]]></title><description><![CDATA[Post inspired by RecyclerCalendarAndroid Lib

RecyclerView
The theory is simple, we need each day of the calendar rendered as one cell of the RecyclerView.
To achieve this, we need to first prepare list of all dates, but there is a problem, we are mi...]]></description><link>https://blog.tejpratapsingh.com/android-how-to-create-custom-calendar-with-recyclerview</link><guid isPermaLink="true">https://blog.tejpratapsingh.com/android-how-to-create-custom-calendar-with-recyclerview</guid><category><![CDATA[Android]]></category><category><![CDATA[library]]></category><category><![CDATA[calendar]]></category><dc:creator><![CDATA[Tej Pratap Singh]]></dc:creator><pubDate>Fri, 03 Feb 2023 05:47:38 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1590252236116/3gv7HG5Az.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<blockquote>
<p>Post inspired by <a target="_blank" href="https://github.com/tejpratap46/RecyclerCalendarAndroid">RecyclerCalendarAndroid Lib</a></p>
</blockquote>
<h3 id="heading-recyclerview">RecyclerView</h3>
<p>The theory is simple, we need each day of the calendar rendered as one cell of the RecyclerView.</p>
<p>To achieve this, we need to first prepare list of all dates, but there is a problem, we are missing a few things:</p>
<ol>
<li><p>Header Cell for Month with span size of 7.</p>
</li>
<li><p>Preceding empty cell (if the month start from Wednesday, we need to add an empty cell with a span of 2)</p>
</li>
<li><p>Succeeding empty cell (if the month ends on a Friday, then we need to add an empty cell with a span of 2)</p>
</li>
</ol>
<p>Now we need to achieve this,</p>
<p>we need to iterate from our start date to the end date:</p>
<pre><code class="lang-kotlin"><span class="hljs-keyword">while</span> (startCalendar.time.before(endCalendar.time) || startCalendar.time == endCalendar.time) {
    <span class="hljs-comment">//...</span>
}
</code></pre>
<p>Now, inside out while loop, we check if the date is the first date of the month, we add our empty cell before we add an actual cell with a date.</p>
<pre><code class="lang-kotlin"><span class="hljs-keyword">val</span> calendarEmptyHeader: RecyclerCalenderViewItem =
    RecyclerCalenderViewItem(
        date = startCalendar.time,
        spanSize = <span class="hljs-number">7</span>,
        isEmpty = <span class="hljs-literal">false</span>,
        isHeader = <span class="hljs-literal">true</span>
    )
calendarItemList.add(calendarEmptyHeader)

<span class="hljs-keyword">val</span> calendarEmptyWeek: RecyclerCalenderViewItem =
    RecyclerCalenderViewItem(
        date = startCalendar.time,
        spanSize = <span class="hljs-number">1</span>,
        isEmpty = <span class="hljs-literal">true</span>,
        isHeader = <span class="hljs-literal">false</span>
    )
<span class="hljs-keyword">if</span> (dayOfWeek - <span class="hljs-number">1</span> &lt; <span class="hljs-number">0</span>) {
    dayOfWeek = <span class="hljs-number">7</span> + (dayOfWeek - <span class="hljs-number">1</span>)
    calendarEmptyWeek.spanSize = dayOfWeek
} <span class="hljs-keyword">else</span> {
    calendarEmptyWeek.spanSize = dayOfWeek - <span class="hljs-number">1</span>
}
<span class="hljs-keyword">if</span> (calendarEmptyWeek.spanSize &gt; <span class="hljs-number">0</span>) {
    <span class="hljs-comment">// Is span size is greater then 0, then add empty cell</span>
    calendarItemList.add(calendarEmptyWeek)
}
</code></pre>
<p>Now, after you added an empty cell, just add the actual date and increment the start date by 1 day</p>
<pre><code class="lang-kotlin"><span class="hljs-keyword">val</span> calendarDateItem: RecyclerCalenderViewItem =
    RecyclerCalenderViewItem(
        date = startCalendar.time,
        spanSize = <span class="hljs-number">1</span>,
        isEmpty = <span class="hljs-literal">false</span>,
        isHeader = <span class="hljs-literal">false</span>
    )
calendarItemList.add(calendarDateItem)
startCalendar.add(Calendar.DATE, <span class="hljs-number">1</span>)
</code></pre>
<p>After doing all that in the while loop, we now have a list with all the dates, headers and empty cells.</p>
<p>Use this list as input to your <code>RecyclerView</code> and render each date, month and empty cell with different views, customize them as per your need.</p>
<h1 id="heading-or">Or</h1>
<p>Simply use this library, customize your views as per your need, supports events, and add additional views and animations, the possibilities are endless.</p>
<div class="embed-wrapper"><div class="embed-loading"><div class="loadingRow"></div><div class="loadingRow"></div></div><a class="embed-card" href="https://github.com/tejpratap46/RecyclerCalendarAndroid">https://github.com/tejpratap46/RecyclerCalendarAndroid</a></div>
]]></content:encoded></item><item><title><![CDATA[How to run Multiple Transitions in Android at Once]]></title><description><![CDATA[Transitions in Android help users navigate from one screen to another with a smooth animation.
There are mainly 2 ways you can create and attach a transition.

Create a res/anim resource and attach it to fragment transaction via setCustomAnimations

...]]></description><link>https://blog.tejpratapsingh.com/how-to-run-multiple-transitions-in-android-at-once</link><guid isPermaLink="true">https://blog.tejpratapsingh.com/how-to-run-multiple-transitions-in-android-at-once</guid><category><![CDATA[Android]]></category><dc:creator><![CDATA[Tej Pratap Singh]]></dc:creator><pubDate>Mon, 23 Jan 2023 12:55:25 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/stock/unsplash/0OIYhfHqooY/upload/d103bf17f72852428c300fd059b7ba65.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Transitions in Android help users navigate from one screen to another with a smooth animation.</p>
<p>There are mainly 2 ways you can create and attach a transition.</p>
<ol>
<li><p>Create a <code>res/anim</code> resource and attach it to fragment transaction via <code>setCustomAnimations</code></p>
</li>
<li><p>Create a <code>res/transition</code> resource and attach it to fragment via <code>setEnterTransition</code> and <code>setExitTransition</code></p>
</li>
</ol>
<h3 id="heading-via-setcustomanimationshttpsdeveloperandroidcomreferenceandroidxfragmentappfragmenttransactionsetcustomanimationsint20int">via <a target="_blank" href="https://developer.android.com/reference/androidx/fragment/app/FragmentTransaction#setCustomAnimations(int,%20int)"><code>setCustomAnimations</code></a></h3>
<p>Simplest way to set custom transition animation is via <code>setCustomAnimations</code> which accepts 4 animation files, one for each transition.</p>
<pre><code class="lang-kotlin"><span class="hljs-keyword">val</span> fragment = FragmentB()
supportFragmentManager.commit {
    setCustomAnimations(
        enter = R.anim.slide_in,
        exit = R.anim.fade_out,
        popEnter = R.anim.fade_in,
        popExit = R.anim.slide_out
    )
    replace(R.id.fragment_container, fragment)
    addToBackStack(<span class="hljs-literal">null</span>)
}
</code></pre>
<p>All transitions will be part of your <code>res/anim</code> folder.</p>
<p>Pros:</p>
<ul>
<li><p>Simplest way to add a transition.</p>
</li>
<li><p>Supports all build-in animations such as <code>scale</code>, <code>Fade</code>, <code>translate</code> etc.</p>
</li>
<li><p>Handles most common scenarios.</p>
</li>
</ul>
<p>Cons:</p>
<ul>
<li>Cannot fine-tune transitions based of <code>Views</code>. Transition will be applied to whole view.</li>
</ul>
<p>To overcome the above limitation, android has another method to attach a transition.</p>
<h3 id="heading-via-setentertransitionhttpsdeveloperandroidcomreferenceandroidappfragmentsetentertransitionandroidtransitiontransition-or-setexittransitionhttpsdeveloperandroidcomreferenceandroidappfragmentsetexittransitionandroidtransitiontransition">Via <a target="_blank" href="https://developer.android.com/reference/android/app/Fragment#setEnterTransition(android.transition.Transition)"><code>setEnterTransition</code></a> Or <a target="_blank" href="https://developer.android.com/reference/android/app/Fragment#setExitTransition(android.transition.Transition)"><code>setExitTransition</code></a></h3>
<p><code>setEnterTransition</code> and <code>setExitTransition</code> work differently than <code>setCustomAnimations</code> as they accept Transition Object instead of animation, we need to create transitions in <code>res/transition</code> folder.</p>
<p>Pros:</p>
<ul>
<li><p>Instead of running animation on complete view, a transition will run transition on all the child view's and their child views if they have any background.</p>
</li>
<li><p>We can exclude a view from transition with <code>excludeTarget(</code><a target="_blank" href="http://R.id"><code>R.id</code></a><code>.view_to_exclude, true)</code> . Transition will run on all views except this view and its children.</p>
</li>
<li><p>Similarly, you can add a view to transition using <code>addTarget(</code><a target="_blank" href="http://R.id"><code>R.id</code></a><code>.rv_bottom_widget_list)</code> . Transition will only run on this view and exclude all other views in the fragment.</p>
</li>
</ul>
<p>Now we can come to the part where we run multiple transitions on same fragment.</p>
<h3 id="heading-running-multiple-transitions-at-once">Running Multiple Transitions At Once</h3>
<p>We can use <code>TransitionSet</code> to create a set of all the transitions that we want to run together. The only caveat is:</p>
<blockquote>
<p><strong>You can only run one type of transition only once per view</strong></p>
</blockquote>
<p>Q. What does it mean?</p>
<p>A. For example, if you are running <code>Fade</code> transition on a <code>layout</code> then that it's child, a <code>imageView</code> cannot have another <code>Fade</code> transition which goes on for a longer duration. You have only one choice, remove <code>imageVIew</code> from 1st transition and add only <code>imageView</code> in the second Fade Transition.</p>
<pre><code class="lang-kotlin"><span class="hljs-comment">// Remove imageView from parent transition, this will remove Fade transition only from imageView</span>
<span class="hljs-keyword">val</span> firstTransition = new Fade().excludeTarget(R.id.imageView, <span class="hljs-literal">true</span>)
<span class="hljs-comment">// add second fade transition to imageView so second transition will only run on imageView</span>
<span class="hljs-keyword">val</span> secondTransition = new Fade().addTarge(R.id.imageVIew)
</code></pre>
<h3 id="heading-add-delay-to-transition">Add delay to transition</h3>
<ul>
<li><p>With <code>setStarteDelay</code> : You can add delay with <code>setStartDelay(long delay)</code>. It will ask the transition to run after a specified delay.</p>
<pre><code class="lang-kotlin">  new Fade().setStartDelay(<span class="hljs-number">1000</span>)
</code></pre>
</li>
</ul>
<ul>
<li><p>with <code>setOrdering</code> : You can also create a <code>TransitionSet</code> and make it execute sequentially so each transition will execute one after another.</p>
<pre><code class="lang-kotlin">  TransitionSet()
      .setOrdering(TransitionSet.ORDERING_SEQUENTIAL)
</code></pre>
</li>
<li><p>With <code>Interpolator</code> : interpolator allows you to return different time value instead of a linear time. With this, you can return time value as <code>zero</code> until you want to start your animation.</p>
<pre><code class="lang-kotlin">  <span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">SlideInterpolator</span> <span class="hljs-title">implements</span> <span class="hljs-title">TimeInterpolator</span> </span>{
      <span class="hljs-keyword">public</span> SlideInterpolator() {
      }

      <span class="hljs-meta">@Override</span>
      <span class="hljs-keyword">public</span> float getInterpolation(float input) {
          float <span class="hljs-keyword">out</span>;
          <span class="hljs-keyword">if</span> (input &lt; <span class="hljs-number">0.5f</span>) {
              <span class="hljs-keyword">out</span> = <span class="hljs-number">0</span>;
          } <span class="hljs-keyword">else</span> {
              <span class="hljs-keyword">out</span> = input;
          }
          <span class="hljs-keyword">return</span> <span class="hljs-keyword">out</span>;
      }
  }
</code></pre>
</li>
</ul>
]]></content:encoded></item><item><title><![CDATA[Android Studio/IntelliJ: How to break on NullPointer or any other Excetion]]></title><description><![CDATA[Sometimes when you are running tests in Android Studio or Intellij Idea, you might face a failed case with following error statement:

test should never throw an exception to this level

Cause of these errors are usually NullPointer or some other Exc...]]></description><link>https://blog.tejpratapsingh.com/android-studiointellij-how-to-break-on-nullpointer-or-any-other-excetion</link><guid isPermaLink="true">https://blog.tejpratapsingh.com/android-studiointellij-how-to-break-on-nullpointer-or-any-other-excetion</guid><category><![CDATA[Android]]></category><category><![CDATA[intellij]]></category><category><![CDATA[Android Studio]]></category><category><![CDATA[Testing]]></category><dc:creator><![CDATA[Tej Pratap Singh]]></dc:creator><pubDate>Tue, 15 Nov 2022 11:16:23 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/unsplash/w1sYdquxs-I/upload/v1668510459463/H1B2RVyJl-.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Sometimes when you are running tests in Android Studio or Intellij Idea, you might face a failed case with following error statement:</p>
<blockquote>
<p>test should never throw an exception to this level</p>
</blockquote>
<p>Cause of these errors are usually <code>NullPointer</code> or some other Exception which is not handled properly and statement is not clear where this Exception might be.</p>
<p>Now we can use Debugger to find exact line which is causing this failure.</p>
<p>Here are the steps on how:</p>
<ol>
<li>Press <code>ctrl+shift+F8</code> or search for 'View Breakpoints'</li>
</ol>
<p>You will see a dialog like this:
<img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1668510612650/O34iADbDd.png" alt="image.png" /></p>
<ol>
<li><p>Check 'Any Exception' checkbox. It will now tell debugger to pause on any line that throws any uncaught exception.</p>
</li>
<li><p>Debug you test case and you will get the exact line that is causing this failure.</p>
</li>
</ol>
]]></content:encoded></item><item><title><![CDATA[Mockito: ArgumentMatcher vs ArgumentCaptor]]></title><description><![CDATA[Mockito.when() allows us to mock behavior of methods in that class. But in order to achieve this we need to mock supplied parameters exactly as our source class expected, If any of our parameter is mismatched, our method will not be mocked and it wil...]]></description><link>https://blog.tejpratapsingh.com/mockito-argumentmatcher-vs-argumentcaptor</link><guid isPermaLink="true">https://blog.tejpratapsingh.com/mockito-argumentmatcher-vs-argumentcaptor</guid><category><![CDATA[Android]]></category><category><![CDATA[mockito]]></category><category><![CDATA[Java]]></category><category><![CDATA[Testing]]></category><dc:creator><![CDATA[Tej Pratap Singh]]></dc:creator><pubDate>Wed, 19 Oct 2022 13:17:46 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/unsplash/jLwVAUtLOAQ/upload/v1666185411937/z3BQDln8R.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p><code>Mockito.when()</code> allows us to mock behavior of methods in that class. But in order to achieve this we need to mock supplied parameters exactly as our source class expected, If any of our parameter is mismatched, our method will not be mocked and it will return <code>null</code> as a result.</p>
<p>We can avoid this by using <strong>ArgumentMatcher</strong> and <strong>ArgumentCaptor</strong>.</p>
<p>Here is a simple example:</p>
<pre><code class="lang-Java"><span class="hljs-comment">// This is a simple method that has to be mocked</span>
<span class="hljs-keyword">final</span> <span class="hljs-keyword">int</span> addition = calculator.getAddition(<span class="hljs-number">2</span>, <span class="hljs-number">3</span>);
</code></pre>
<pre><code class="lang-Java"><span class="hljs-comment">// For cases, where you do not know exact parameter then you can use Mockito.anyInt()</span>
Mockito.when(mckCalculator.getAddition(Mockito.anyInt(), Mockito.anyInt())).thenReturn(<span class="hljs-number">5</span>);
</code></pre>
<p>These <code>any</code> matchers comes too handy when parameters are either computed by program or you simply want to assert if correct parameter are passed to the method.</p>
<p>Similar to <code>any()</code>, we also have type specific matchers, but keep in mind these matcher will not work if your argument is null.</p>
<p>Here is a list of all other matchers available to you:</p>
<p>Mockito.anyInt(), Mockito.anyLong(), Mockito.anyString(), Mockito.anyBoolean(), Mockito.anyByte(), Mockito.anyChar(), Mockito.anyFloat(), Mockito.anyDouble(), Mockito.anyShort(), Mockito.anyList(), Mockito.anySet() and Mockito.anyMap()</p>
<p>Lets see an example:
We have a <code>TaskManager.class</code> which will be mocked eventually.</p>
<pre><code class="lang-Java"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">TaskManager</span> </span>{
    <span class="hljs-keyword">private</span> Map&lt;String, Task&gt; taskMap = <span class="hljs-keyword">new</span> ConcurrentHashMap&lt;&gt;();
    <span class="hljs-function"><span class="hljs-keyword">public</span> Task <span class="hljs-title">createTask</span><span class="hljs-params">(String name)</span> </span>{
        <span class="hljs-keyword">final</span> task = <span class="hljs-keyword">new</span> Task();
        taskMap.put(name, task);
        <span class="hljs-keyword">return</span> task;
    }

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">deleteTask</span><span class="hljs-params">(String name)</span> </span>{
        taskMap.remove(name);
    }

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">executeTask</span><span class="hljs-params">(String name, Runnable runnable)</span> </span>{
        <span class="hljs-comment">// Some long running task</span>
        runnable.run();
    }
}
</code></pre>
<p>We have another class which uses <code>TaskManager.class</code> internally, lets call it <code>ExampleWorker</code>. We have to write tests for <code>ExampleWorker</code>.</p>
<pre><code class="lang-Java"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">ExampleWorker</span> </span>{
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">final</span> String TASK_NAME = <span class="hljs-string">"exampleWorkedTask"</span>;

    <span class="hljs-keyword">private</span> <span class="hljs-keyword">final</span> TaskManager mTaskManager;
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">final</span> Task mTask;

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">ExampleTask</span><span class="hljs-params">(TaskManager taskManager)</span> </span>{
        mTaskManager = taskManager;
        mTask = mTaskManager.createTask(TASK_NAME);
    }

    <span class="hljs-function"><span class="hljs-keyword">public</span> Task <span class="hljs-title">getTask</span><span class="hljs-params">()</span> </span>{
        <span class="hljs-keyword">return</span> mTask;
    }

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">deleteTask</span><span class="hljs-params">()</span> </span>{
        mTaskManager.deleteTask(TASK_NAME);
        mTask = <span class="hljs-keyword">null</span>;
    }

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">runTask</span><span class="hljs-params">()</span> </span>{
        mTaskManager.executeTask(TASK_NAME, <span class="hljs-keyword">new</span> Runnable() {
            <span class="hljs-meta">@Override</span>
            <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">run</span><span class="hljs-params">()</span> </span>{
                <span class="hljs-comment">// Do something here</span>
            }
        });
    }
}
</code></pre>
<p>We can write test for <code>ExampleWorker</code> as below:</p>
<pre><code class="lang-Java"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">ExampleWorkerTest</span> </span>{
    <span class="hljs-keyword">private</span> ExampleWorker classUnderTest;

    <span class="hljs-keyword">private</span> TaskManager mckTaskManager;

    <span class="hljs-meta">@Before</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">setUp</span><span class="hljs-params">()</span> <span class="hljs-keyword">throws</span> Exception </span>{
        mckTaskManager = Mockito.mock(TaskManager.class);

        classUnderTest = <span class="hljs-keyword">new</span> ExampleWorker(mckTaskManager);
    }

    <span class="hljs-meta">@After</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">tearDown</span><span class="hljs-params">()</span> <span class="hljs-keyword">throws</span> Exception </span>{
        classUnderTest = <span class="hljs-keyword">null</span>;
    }

    <span class="hljs-meta">@Test</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">constructor_shouldCreateTask</span><span class="hljs-params">()</span> </span>{
        <span class="hljs-comment">// Then</span>
        <span class="hljs-keyword">final</span> Task actualResult = classUnderTest.getTask();
        Assert.assertNotNull(actualResult);
    }
}
</code></pre>
<p>Now comes the fun part where we try to test <code>deleteTask()</code> method which will internally call <code>TaskManager</code>'s <code>deleteTask(taskName)</code> method.</p>
<p>We can write simple tests with <strong>ArgumentMatcher</strong>.</p>
<pre><code class="lang-Java"><span class="hljs-meta">@Test</span>
<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">deleteTask_shouldRemoveTask</span><span class="hljs-params">()</span> </span>{
    <span class="hljs-comment">// Given</span>
    <span class="hljs-comment">// There are multiple ways to mock same statement, use eany one of these three based on your requirement</span>
    <span class="hljs-comment">// You can match exact parameter</span>
    Mockito.doNothing().when(mckTaskManager).deleteTask(<span class="hljs-string">"exampleWorkedTask"</span>);
    <span class="hljs-comment">// You can match anyString(), but it will not work when string is null</span>
    Mockito.doNothing().when(mckTaskManager).deleteTask(Mockito.anyString());
    <span class="hljs-comment">// You can match any(), it will work even if parameter String is null</span>
    Mockito.doNothing().when(mckTaskManager).deleteTask(Mockito.any());

    <span class="hljs-comment">// When</span>
    classUnderTest.deleteTask();

    <span class="hljs-comment">// Then</span>
    <span class="hljs-keyword">final</span> Task actualResult = classUnderTest.getTask();
    Assert.assertNotNull(actualResult);
}
</code></pre>
<p>But what if we want to assert on the parameters passed while calling <code>deleteTask(taskName)</code> method, we can use <strong>ArgumentCaptor</strong></p>
<pre><code class="lang-Java"><span class="hljs-meta">@Test</span>
<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">deleteTask_shouldRemoveTask_assertWithArgumenCaptor</span><span class="hljs-params">()</span> </span>{
    <span class="hljs-comment">// Given</span>
    <span class="hljs-keyword">final</span> ArgumentCaptor&lt;String&gt; taskNameArgumentMatcher = ArgumentCaptor.forClass(String.class);
    <span class="hljs-comment">// You can create a captor and validate</span>
    Mockito.doNothing().when(mckTaskManager).deleteTask(taskNameArgumentMatcher.captor());

    <span class="hljs-comment">// When</span>
    classUnderTest.deleteTask();

    <span class="hljs-comment">// Then</span>
    <span class="hljs-comment">// Now we can get the value from taskNameArgumentMatcher and assert it with expectedValue</span>
    <span class="hljs-keyword">final</span> String actualTaskName = taskNameArgumentMatcher.getValue();
    Assert.assertEquals(<span class="hljs-string">"exampleWorkedTask"</span>, actualTaskName);
}
</code></pre>
<p>But guess what, you can also get parameters used with <strong><em>ArgumentMatcher</em></strong> same as <strong><em>ArgumentCaptor</em></strong>. Here is an example:</p>
<pre><code class="lang-Java"><span class="hljs-meta">@Test</span>
<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">deleteTask_shouldRemoveTask_assertWithArgumenMatcher</span><span class="hljs-params">()</span> </span>{
    <span class="hljs-comment">// Given</span>
    <span class="hljs-keyword">final</span> AtomicReference&lt;String&gt; taskNameReference = <span class="hljs-keyword">new</span> AtomicReference&lt;&gt;();
    Mockito.doAnswer(invocation -&gt; {
        taskNameReference.set(<span class="hljs-number">0</span>, invocation.getArgument(<span class="hljs-number">0</span>, String.class));
        <span class="hljs-keyword">return</span> <span class="hljs-keyword">null</span>;
    }).when(mckTaskManager).deleteTask(Mockito.anyString());

    <span class="hljs-comment">// When</span>
    classUnderTest.deleteTask();

    <span class="hljs-comment">// Then</span>
    <span class="hljs-comment">// Now we can get the value from taskNameArgumentMatcher and assert it with expectedValue</span>
    <span class="hljs-keyword">final</span> String actualTaskName = taskNameReference.get();
    Assert.assertEquals(<span class="hljs-string">"exampleWorkedTask"</span>, actualTaskName);
}
</code></pre>
<p>P.S. ArgumentMatcher and ArgumentCaptor both  work in a similar way difference is just with the syntax. <strong>ArgumentCaptor</strong> gives clear API to assert the values passed while <strong>ArgumentMatcher</strong> was general purpose matchers that can do everything.</p>
]]></content:encoded></item><item><title><![CDATA[PowerMock: Understanding @PrepareForTest]]></title><description><![CDATA[PowerMock is a powerful library that works on byte code level of our program.
This blog will only talk about when and how you need to use @PrepareForTest. If you need to know more about other things PowerMock can do, read this one first
PrepareForTes...]]></description><link>https://blog.tejpratapsingh.com/powermock-understanding-preparefortest</link><guid isPermaLink="true">https://blog.tejpratapsingh.com/powermock-understanding-preparefortest</guid><category><![CDATA[PowerMock]]></category><category><![CDATA[Android]]></category><category><![CDATA[Java]]></category><category><![CDATA[Testing]]></category><category><![CDATA[Mocking]]></category><dc:creator><![CDATA[Tej Pratap Singh]]></dc:creator><pubDate>Tue, 18 Oct 2022 12:00:47 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/unsplash/5IHz5WhosQE/upload/v1666094382234/L84bxjkI5.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>PowerMock is a powerful library that works on byte code level of our program.</p>
<p>This blog will only talk about when and how you need to use <code>@PrepareForTest</code>. If you need to know more about other things PowerMock can do, <a target="_blank" href="https://blog.tejpratapsingh.com/powermock-cheatsheet-tldr-and-tips-cl9cvkr9q000h09l685g2dqhe">read this one first</a></p>
<h2 id="heading-preparefortest-annotation">PrepareForTest annotation</h2>
<p>PrepareForTest has one job, it will creates a reflection of your class at bytecode level. It allows you to manipulate your source code such that you can change behavior (implementation) of declared methods.</p>
<p>This comes handy when you are working with class or methods that are now allowed to be mocked by Java Reflection.</p>
<p>Here are some f the use cases for PrepareForTest:</p>
<ol>
<li>mock static methods<pre><code class="lang-Java"><span class="hljs-meta">@RunWith(PowerMockRunner.class)</span>
<span class="hljs-meta">@PrepareForTest({
 ClassWithStaticMethods.class,
})</span>
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">ClassToTest</span> </span>{
 <span class="hljs-meta">@Before</span>
 <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">setUp</span><span class="hljs-params">()</span> <span class="hljs-keyword">throws</span> Exception </span>{
     PowerMockito.mockStatic(ClassWithStaticMethods.class);
     PowerMockito.when(ClassWithStaticMethods.staticMethod()).thenReturn(someValue);
 }
}
</code></pre>
</li>
<li><p>mock final classes/methods:
Mockito cannot mock final methods even if you have created mock of that class. To mock these methods, we need to prepare that class and mock it with <code>PowerMockito.mock()</code>.</p>
<pre><code class="lang-Java"><span class="hljs-meta">@RunWith(PowerMockRunner.class)</span>
<span class="hljs-meta">@PrepareForTest({
 FinalClass.class,
 ClassWithFinalMethods.class,
})</span>
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">ClassToTest</span> </span>{
 <span class="hljs-meta">@Test</span>
 <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">testFinalMethods</span><span class="hljs-params">()</span> <span class="hljs-keyword">throws</span> Exception </span>{
     <span class="hljs-keyword">final</span> FinalClass mckFinalClass = PowerMockito.mock(FinalClass.class);
     PowerMockito.when(mckFinalClass.someMethod()).thenReturn(someValue);

     <span class="hljs-keyword">final</span> ClassWithFinalMethods mckClassWithFinalMethods = PowerMockito.mock(ClassWithFinalMethods.class);
     PowerMockito.when(mckClassWithFinalMethods.someFinalMethod()).thenReturn(someValue);
 }
}
</code></pre>
</li>
<li><p>Inject with PowerMockito.whenNew()
When you need to inject a mock instead of creating an actual instance of a class, you can use <code>PowerMockito.whenNew()</code>. This will inject your mock whenever new instance is created in your source class.</p>
<pre><code class="lang-Java"><span class="hljs-comment">// Example Source Class</span>
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">ExampleClass</span> </span>{
 <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">int</span> <span class="hljs-title">getHeight</span><span class="hljs-params">()</span> </span>{
     <span class="hljs-comment">// Lets say we have a generic method which provides different result base on the provided id</span>
     <span class="hljs-keyword">final</span> CustomClass customClassInstance = <span class="hljs-keyword">new</span> CustomClass();
     <span class="hljs-keyword">return</span> customClass.getHeight();
 }
}
</code></pre>
<p>In this example class, we are creating <code>CustomClass</code> without any injection mechanism, we can inject our mock by adding <code>ExampleClass</code> in <code>PrepareForTest</code> and using <code>PowerMockito.whenNew()</code>:</p>
<pre><code class="lang-Java"><span class="hljs-meta">@RunWith(PowerMockRunner.class)</span>
<span class="hljs-meta">@PrepareForTest({
 ExampleClass.class
})</span>
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">ExampleClassTest</span> </span>{

 <span class="hljs-keyword">private</span> ExampleClass classUnderTest;

 <span class="hljs-meta">@Before</span>
 <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">setUp</span><span class="hljs-params">()</span> <span class="hljs-keyword">throws</span> Exception </span>{
     <span class="hljs-comment">// Create constructor of ExampleClass</span>
     classUnderTest = <span class="hljs-keyword">new</span> ExampleClass();
 }

 <span class="hljs-meta">@Test</span>
 <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">getHeight_shoudReturnHeightOfView</span><span class="hljs-params">()</span> <span class="hljs-keyword">throws</span> NoSuchMethodException </span>{
     <span class="hljs-keyword">final</span> <span class="hljs-keyword">int</span> expectedHeight = <span class="hljs-number">100</span>;
     <span class="hljs-comment">// Given</span>
     <span class="hljs-keyword">final</span> CustomClass mckCustomClass = Mockito.mock(CustomClass.class);
     Mockito.when(mckCustomClass.getHeight()).theReturn(expectedHeight);
     // <span class="hljs-function">Make sure you match exact parameters <span class="hljs-keyword">while</span> <span class="hljs-title">mocking</span> <span class="hljs-params">(same as we <span class="hljs-keyword">do</span> <span class="hljs-keyword">for</span> Mockito.mock statements)</span>.
     <span class="hljs-comment">// There is also withArguments(first, second, ....)</span>
     <span class="hljs-comment">// and withAnyArguments() for cases when you don't care for arguments passed.</span>
     PowerMockito.<span class="hljs-title">whenNew</span><span class="hljs-params">(CustomClass.class)</span>.<span class="hljs-title">withNoArguments</span><span class="hljs-params">()</span>.<span class="hljs-title">thenReturn</span><span class="hljs-params">(mckCustomClass)</span></span>;

     <span class="hljs-keyword">final</span> <span class="hljs-keyword">int</span> actualResult = classUnderTest.getHeight();

     Assert.assertEquals(expectedHeight, actualResult);
 }
}
</code></pre>
</li>
<li>To <code>suppress()</code>, <code>stub()</code> or <code>replace()</code> any method of a Class.
You can modify behavior of methods declared in any class, You can:</li>
<li><code>suppress()</code> methods and constructors.<pre><code class="lang-Java"><span class="hljs-comment">// Suppress Constructor</span>
PowerMockito.suppress(CustomLibClass.class.getConstructors());
// Suppress Method, it will <span class="hljs-keyword">return</span> <span class="hljs-keyword">null</span> <span class="hljs-keyword">if</span> method has a return.
PowerMockito.suppress(CustomLibClass.class.getDeclaredMethod(<span class="hljs-string">"someMethod"</span>));
</code></pre>
</li>
<li><code>stub()</code> methods to return different value.<pre><code class="lang-Java">PowerMockito.stub(CustomLibClass.class.getDeclaredMethod("someMethodThatOnlyWorksOnRumtime")).toReturn(<span class="hljs-number">2</span>);
</code></pre>
</li>
<li><p><code>replace()</code> methods to return different value depending on parameter supplied.</p>
<pre><code class="lang-Java">PowerMockito.replace(View.class.getDeclaredMethod("someMethodThatWillReturnDifferentValue", <span class="hljs-keyword">int</span>.class)).with(<span class="hljs-keyword">new</span> InvocationHandler() {
  <span class="hljs-meta">@Override</span>
  <span class="hljs-function"><span class="hljs-keyword">public</span> Object <span class="hljs-title">invoke</span><span class="hljs-params">(Object proxy, Method method, Object[] args)</span> <span class="hljs-keyword">throws</span> Throwable </span>{
      <span class="hljs-keyword">final</span> <span class="hljs-keyword">int</span> viewId = (<span class="hljs-keyword">int</span>) args[<span class="hljs-number">0</span>];

      <span class="hljs-keyword">if</span> (viewId == ViewFactory.text_view) {
          <span class="hljs-comment">// return mock of TextView</span>
          <span class="hljs-keyword">return</span> Mockito.mock(TextView.class);
      } <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (viewId == ViewFactory.image_view) {
          <span class="hljs-comment">// return mock of ImageView</span>
          <span class="hljs-keyword">return</span> Mockito.mock(ImageView.class);
      }
      // <span class="hljs-keyword">else</span> you can call real method as well
      <span class="hljs-keyword">return</span> method.invoke(proxy, args);
  }
});
</code></pre>
</li>
</ol>
]]></content:encoded></item><item><title><![CDATA[Powermock CheatSheet: Tldr and Tips]]></title><description><![CDATA[Why we need Powermock?
Although Mockito is most popular Mocking Library for Java Developers, But there are certain cases where Simple Mockito does not work. For Example, if your codebase uses any Singleton, you cannot mock them with Simple Mockito.
T...]]></description><link>https://blog.tejpratapsingh.com/powermock-cheatsheet-tldr-and-tips</link><guid isPermaLink="true">https://blog.tejpratapsingh.com/powermock-cheatsheet-tldr-and-tips</guid><category><![CDATA[PowerMockito]]></category><category><![CDATA[Java]]></category><category><![CDATA[Testing]]></category><category><![CDATA[mockito]]></category><category><![CDATA[Android]]></category><dc:creator><![CDATA[Tej Pratap Singh]]></dc:creator><pubDate>Mon, 17 Oct 2022 14:31:57 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/unsplash/7lIrDouiacw/upload/v1666013124918/4jZhZ7cYF.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h3 id="heading-why-we-need-powermock">Why we need Powermock?</h3>
<p>Although Mockito is most popular Mocking Library for Java Developers, But there are certain cases where Simple Mockito does not work. For Example, if your codebase uses any Singleton, you cannot mock them with Simple Mockito.</p>
<p>There are many other use cases, such as:</p>
<ol>
<li><p>Mock Static Methods</p>
</li>
<li><p>Mock Final Classes and Methods</p>
</li>
<li><p>Inject mock for object creation with <code>whenNew()</code></p>
</li>
<li><p><code>suppress()</code>, <code>stub()</code> or <code>replace()</code> any method of a Class.</p>
</li>
<li><p>Suppress static initialisation.</p>
</li>
<li><p>Invoke private methods.</p>
</li>
<li><p>Inject field with <code>Whitebox</code></p>
</li>
</ol>
<h3 id="heading-1-powermockrunner">1. PowerMockRunner</h3>
<p>You must annotate each class you test with <code>PowerMockRunner</code></p>
<pre><code class="lang-Java"><span class="hljs-meta">@RunWith(PowerMockRunner.class)</span>
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">ClassToTest</span> </span>{
}
</code></pre>
<h3 id="heading-2-preparefortest">2. PrepareForTest</h3>
<p>Each class you add in <code>@PrepareForTest</code> will generate an different bytecode that can be manipulated by PowerMock.</p>
<pre><code class="lang-Java"><span class="hljs-meta">@RunWith(PowerMockRunner.class)</span>
<span class="hljs-meta">@PrepareForTest({
    StaticClass.class,
    FinalClass.class,
    ClassWithFinalMethod.class
})</span>
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">ClassToTest</span> </span>{
}
</code></pre>
<p>PreparingForTest unlocks class for a wide variety of things such as mocking final classes, classes with final, private, static or native methods that should be mocked and also classes that should be return a mock object upon instantiation.</p>
<p>You can read more about what <code>@PrepareForTest</code> unlocks from <a target="_blank" href="https://blog.tejpratapsingh.com/powermock-understanding-preparefortest">here</a></p>
<h3 id="heading-3-suppressstaticinitializationfor">3. SuppressStaticInitializationFor</h3>
<p>If you are working with classes which have static initializers such as:</p>
<pre><code class="lang-java"><span class="hljs-keyword">package</span> com.example;

<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">ClassWithStaticInitializer</span> </span>{
        <span class="hljs-keyword">private</span> <span class="hljs-keyword">static</span> Handler mHandler = <span class="hljs-keyword">new</span> Handler();
}
</code></pre>
<p>As <code>mHandler</code> belongs to <code>ClassWithStaticInitializer.class</code> not instance of <code>ClassWithStaticInitializer</code>, JVM will initialize this <code>mHandler</code> as soon as execution starts, thus we will not get a chance to mock it with <code>whenNew()</code>. In this case, we can suppress its initialization and later set its value with <code>Whitebox</code>.</p>
<p>Here is an example to suppress <code>mHandler</code> in <code>ClassWithStaticInitializer.class</code>:</p>
<pre><code class="lang-Java"><span class="hljs-meta">@RunWith(PowerMockRunner.class)</span>
<span class="hljs-meta">@SuppressStaticInitializationFor({
        "com.example.ClassWithStaticInitializer"
})</span>
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">ClassWithStaticInitializerTest</span> </span>{
        <span class="hljs-comment">// now when we call</span>
        <span class="hljs-meta">@Before</span>
        <span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> setup <span class="hljs-keyword">throws</span> Exception {
                <span class="hljs-comment">// At this stage, ClassWithStaticInitializer.mHandler will be null</span>
                Whitebox.setInternalState(ClassWithStaticInitializer.class, <span class="hljs-string">"mHandler"</span>, mckHandler);
        }
}
</code></pre>
<blockquote>
<p><strong>tip:</strong> if you see any error with StackTrace containing similar looking line <code>com.examlpe.ExampleClass.&lt;clinit&gt;</code>. It means there is an static initializer, just add <code>com.examlpe.ExampleClass</code> in your <code>SuppressStaticInitializationFor</code> annotation.</p>
</blockquote>
<h3 id="heading-4-powermockitosuppress">4. PowerMockito.suppress()</h3>
<p><code>suppress()</code> is one of the most powerful API's provided by PowerMock.</p>
<p>With <code>suppress()</code> you can manipulate bytecode to skip executing any method or constructor.</p>
<p>For example, lets say you had an class which extended an library or code that you don't own, you can suppress its constructor.</p>
<pre><code class="lang-Java"><span class="hljs-comment">// Example Source Class</span>
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">ExampleClass</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">CustomLibClass</span> </span>{
      <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">ExampleClass</span><span class="hljs-params">()</span> </span>{
            System.out.println(<span class="hljs-string">"class initialised"</span>);
      }

      <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">someMethod</span><span class="hljs-params">()</span> </span>{
            <span class="hljs-keyword">super</span>.someMethod();
      }
}
</code></pre>
<p>Here, our source class extends <code>CustomLibClass</code> which we do not need to test. But creating a object of <code>ExampleClass</code> will also call constructor of <code>CustomLibClass</code>. This can be avoided if we tell Powermock to suppress constructor of <code>CustomLibClass</code>.</p>
<pre><code class="lang-Java"><span class="hljs-comment">// Test of Example Source Class</span>
<span class="hljs-meta">@RunWith(PowerMockRunner.class)</span>
<span class="hljs-meta">@PrepareForTest({
    ExampleClass.class
})</span>
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">ExampleClassTest</span> </span>{

    <span class="hljs-keyword">private</span> ExampleClass classUnderTest;

    <span class="hljs-meta">@Before</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">setUp</span><span class="hljs-params">()</span> <span class="hljs-keyword">throws</span> Exception </span>{
        <span class="hljs-comment">// We should suppress constructor of CustomLibClass</span>
        <span class="hljs-comment">// There are multiple ways to do that</span>
        <span class="hljs-comment">// 1. Suppress with matching constructor, in below case it will only suppress constructor without any parameter</span>
        PowerMockito.suppress(MemberMatcher.constructor(CustomLibClass.class));
        // Or using Java Reflection
        PowerMockito.suppress(CustomLibClass.class.getConstructor());
        // <span class="hljs-number">2.</span> Suppress all declared constructor
        PowerMockito.suppress(MemberMatcher.constructorsDeclaredIn(CustomLibClass.class));
        // Or Using Java Reflection API's
        PowerMockito.suppress(CustomLibClass.class.getConstructors());

        // Create constructor of ExampleClass, it will not call constructor of CustomLibClass
        classUnderTest = <span class="hljs-keyword">new</span> ExampleClass();
    }

    <span class="hljs-meta">@Test</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">someMethod_shouldDoNothing</span><span class="hljs-params">()</span> </span>{
        <span class="hljs-comment">// This is just an example, it is not necessary for an example test to test something :D</span>
        PowerMockito.suppress(CustomLibClass.class.getDeclaredMethod(<span class="hljs-string">"someMethod"</span>));
    }
}
</code></pre>
<blockquote>
<p>***Note: *** keep in mind, if you need to manipulate behavior (byte code) of any class, as we are doing in case of suppress constructor, we need to add <code>ExampleClass.class</code> in <code>@PrepareForTest</code>.</p>
</blockquote>
<h3 id="heading-5-powermockitostub">5. PowerMockito.stub()</h3>
<p><code>suppress()</code> works best for <code>void</code> methods or constructors, but what if need to return something. For that we have <code>stub()</code>.</p>
<pre><code class="lang-Java"><span class="hljs-comment">// Example Source Class</span>
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">ExampleClass</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">CustomLibClass</span> </span>{
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">int</span> <span class="hljs-title">someMethod</span><span class="hljs-params">()</span> </span>{
        <span class="hljs-keyword">final</span> <span class="hljs-keyword">int</span> valueFromSuper = <span class="hljs-keyword">super</span>.someMethodThatOnlyWorksOnRumtime();
        <span class="hljs-keyword">return</span> valueFromSuper * <span class="hljs-number">2</span>;
    }
}
</code></pre>
<p>Here, we have a method with that return something, and to test our method we need get a fixed value from <code>CustomLibClass.someMethodThatOnlyWorksOnRumtime()</code>. To achive that, we can use <code>stub()</code>.</p>
<pre><code class="lang-Java"><span class="hljs-meta">@RunWith(PowerMockRunner.class)</span>
<span class="hljs-meta">@PrepareForTest({
    ExampleClass.class
})</span>
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">ExampleClassTest</span> </span>{

    <span class="hljs-keyword">private</span> ExampleClass classUnderTest;

    <span class="hljs-meta">@Before</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">setUp</span><span class="hljs-params">()</span> <span class="hljs-keyword">throws</span> Exception </span>{
        <span class="hljs-comment">// Create constructor of ExampleClass</span>
        classUnderTest = <span class="hljs-keyword">new</span> ExampleClass();
    }

    <span class="hljs-meta">@Test</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">someMethod_shouldReturnFour_whenCustomLibSomeMethodThatOnlyWorksOnRumtimeReturnTwo</span><span class="hljs-params">()</span> <span class="hljs-keyword">throws</span> NoSuchMethodException </span>{
        <span class="hljs-comment">// Given</span>
        PowerMockito.stub(CustomLibClass.class.getDeclaredMethod("someMethodThatOnlyWorksOnRumtime")).toReturn(<span class="hljs-number">2</span>);

        <span class="hljs-comment">// When</span>
        <span class="hljs-keyword">final</span> <span class="hljs-keyword">int</span> actualResult = classUnderTest.someMethod();

        <span class="hljs-comment">// Then</span>
        <span class="hljs-comment">// As we stubbed someMethodThatOnlyWorksOnRumtime() to return 2, our result will be 2 * 2 = 4</span>
        Assert.assertEquals(<span class="hljs-number">4</span>, actualResult);
    }
}
</code></pre>
<blockquote>
<p>***Note: *** keep in mind, if you need to manipulate behavior (byte code) of any class, as we are doing in case of stub method, we need to add <code>ExampleClass.class</code> in <code>@PrepareForTest</code>.</p>
</blockquote>
<h3 id="heading-5-powermockitoreplace">5. PowerMockito.replace()</h3>
<p><code>stub()</code> works best when we don't care about the parameters and want same result irrespective of parameter passed.</p>
<p>With <code>replace()</code> we can go one step ahead of <code>stub()</code>, depending upon the supplied parameters, we can return different results. Let's see another similar example:</p>
<pre><code class="lang-Java"><span class="hljs-comment">// Example Source Class</span>
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">ExampleClass</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Screen</span> </span>{
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">int</span> <span class="hljs-title">getHeaderView</span><span class="hljs-params">()</span> </span>{
        <span class="hljs-comment">// Lets say we have a generic method which provides different result base on the provided id</span>
        <span class="hljs-keyword">final</span> TextView textView = findViewById(ViewFactory.text_view);
        textView.setText(<span class="hljs-string">"Header"</span>);
        <span class="hljs-keyword">final</span> ImageView imageView  = findViewById(ViewFactory.image_view);
        imageView.setImage(BitmapFactory.getUserProfileImage());
        <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> HStack(textView, imageView);
    }
}
</code></pre>
<p>Now, if we want to test our method with dynamic values, maybe you need to return different values based on parameter.</p>
<pre><code class="lang-Java"><span class="hljs-meta">@RunWith(PowerMockRunner.class)</span>
<span class="hljs-meta">@PrepareForTest({
    ExampleClass.class
})</span>
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">ExampleClassTest</span> </span>{

    <span class="hljs-keyword">private</span> ExampleClass classUnderTest;

    <span class="hljs-meta">@Before</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">setUp</span><span class="hljs-params">()</span> <span class="hljs-keyword">throws</span> Exception </span>{
        <span class="hljs-comment">// Create constructor of ExampleClass</span>
        classUnderTest = <span class="hljs-keyword">new</span> ExampleClass();
    }

    <span class="hljs-meta">@Test</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">getHeaderView_shoudReturnHStack</span><span class="hljs-params">()</span> <span class="hljs-keyword">throws</span> NoSuchMethodException </span>{
        <span class="hljs-comment">// Given</span>
        PowerMockito.replace(View.class.getDeclaredMethod("someMethodThatWillReturnDifferentValue", <span class="hljs-keyword">int</span>.class)).with(<span class="hljs-keyword">new</span> InvocationHandler() {
            <span class="hljs-meta">@Override</span>
            <span class="hljs-function"><span class="hljs-keyword">public</span> Object <span class="hljs-title">invoke</span><span class="hljs-params">(Object proxy, Method method, Object[] args)</span> <span class="hljs-keyword">throws</span> Throwable </span>{
                <span class="hljs-keyword">final</span> <span class="hljs-keyword">int</span> viewId = (<span class="hljs-keyword">int</span>) args[<span class="hljs-number">0</span>];

                <span class="hljs-keyword">if</span> (viewId == ViewFactory.text_view) {
                    <span class="hljs-comment">// return mock of TextView</span>
                    <span class="hljs-keyword">return</span> Mockito.mock(TextView.class);
                } <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (viewId == ViewFactory.image_view) {
                    <span class="hljs-comment">// return mock of ImageView</span>
                    <span class="hljs-keyword">return</span> Mockito.mock(ImageView.class);
                }
                // <span class="hljs-keyword">else</span> you can call real method as well
                <span class="hljs-keyword">return</span> method.invoke(proxy, args);
            }
        });

        <span class="hljs-comment">// When</span>
        <span class="hljs-keyword">final</span> HStack actualResult = classUnderTest.getHeaderView();

        Assert.assertNotNull(actualResult);
    }
}
</code></pre>
<blockquote>
<p>***Note: *** keep in mind, if you need to manipulate behavior (byte code) of any class, as we are doing in case of replace method, we need to add <code>ExampleClass.class</code> in <code>@PrepareForTest</code>.</p>
</blockquote>
<h3 id="heading-6-powermockitowhennew">6. PowerMockito.whenNew()</h3>
<p>There are some cases where source code directly create a new instance of object without any injection mechanism. JVM will create an instance with actual class with actual methods. For these cases, we can use <code>PowerMockito.whenNew()</code> method to</p>
<p>Similar to Mockito's <code>when()</code> statement, we can tell PowerMock to inject our mock instead of creating new instance of real object.</p>
<p>Here is an example:</p>
<pre><code class="lang-Java"><span class="hljs-comment">// Example Source Class</span>
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">ExampleClass</span> </span>{
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">int</span> <span class="hljs-title">getHeight</span><span class="hljs-params">()</span> </span>{
        <span class="hljs-comment">// Lets say we have a generic method which provides different result base on the provided id</span>
        <span class="hljs-keyword">final</span> CustomClass customClassInstance = <span class="hljs-keyword">new</span> CustomClass();
        <span class="hljs-keyword">return</span> customClass.getHeight();
    }
}
</code></pre>
<p>In above example, CustomClass instance is created without any mechanism to inject it, lets see how can we tell PowerMockito to inject our mock.</p>
<pre><code class="lang-Java"><span class="hljs-meta">@RunWith(PowerMockRunner.class)</span>
<span class="hljs-meta">@PrepareForTest({
    ExampleClass.class
})</span>
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">ExampleClassTest</span> </span>{

    <span class="hljs-keyword">private</span> ExampleClass classUnderTest;

    <span class="hljs-meta">@Before</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">setUp</span><span class="hljs-params">()</span> <span class="hljs-keyword">throws</span> Exception </span>{
        <span class="hljs-comment">// Create constructor of ExampleClass</span>
        classUnderTest = <span class="hljs-keyword">new</span> ExampleClass();
    }

    <span class="hljs-meta">@Test</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">getHeight_shoudReturnHeightOfView</span><span class="hljs-params">()</span> <span class="hljs-keyword">throws</span> NoSuchMethodException </span>{
        <span class="hljs-keyword">final</span> <span class="hljs-keyword">int</span> expectedHeight = <span class="hljs-number">100</span>;
        <span class="hljs-comment">// Given</span>
        <span class="hljs-keyword">final</span> CustomClass mckCustomClass = Mockito.mock(CustomClass.class);
        Mockito.when(mckCustomClass.getHeight()).theReturn(expectedHeight);
        // <span class="hljs-function">Make sure you match exact parameters <span class="hljs-keyword">while</span> <span class="hljs-title">mocking</span> <span class="hljs-params">(same as we <span class="hljs-keyword">do</span> <span class="hljs-keyword">for</span> Mockito.mock statements)</span>.
        <span class="hljs-comment">// There is also withArguments(first, second, ....)</span>
        <span class="hljs-comment">// and withAnyArguments() for cases when you don't care for arguments passed.</span>
        PowerMockito.<span class="hljs-title">whenNew</span><span class="hljs-params">(CustomClass.class)</span>.<span class="hljs-title">withNoArguments</span><span class="hljs-params">()</span>.<span class="hljs-title">thenReturn</span><span class="hljs-params">(mckCustomClass)</span></span>;

        <span class="hljs-keyword">final</span> <span class="hljs-keyword">int</span> actualResult = classUnderTest.getHeight();

        Assert.assertEquals(expectedHeight, actualResult);
    }
}
</code></pre>
<blockquote>
<p>***Note: *** keep in mind, if you need to manipulate behavior (byte code) of any class, as we are doing in case of whenNew() method, we need to add <code>ExampleClass.class</code> in <code>@PrepareForTest</code>. <strong><em>Note</em></strong> Keep in mind, whenNew() will not work when new instance was created inside a nested scope.</p>
</blockquote>
<h3 id="heading-7-whiteboxinvokemethod">7. Whitebox.invokeMethod()</h3>
<p>Used to call an private method, just a wrapper on Java Reflection API's</p>
<pre><code class="lang-Java"><span class="hljs-comment">// Example Source Class</span>
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">ExampleClass</span> </span>{
    <span class="hljs-function"><span class="hljs-keyword">private</span> <span class="hljs-keyword">int</span> <span class="hljs-title">getHeight</span><span class="hljs-params">()</span> </span>{
        <span class="hljs-comment">// Lets say we have a generic method which provides different result base on the provided id</span>
        <span class="hljs-keyword">final</span> CustomClass customClassInstance = <span class="hljs-keyword">new</span> CustomClass();
        <span class="hljs-keyword">return</span> customClass.getHeight();
    }
}
</code></pre>
<p>We can use <code>Whitebox.invokeMethod()</code> to execute that method, here an example:</p>
<pre><code class="lang-Java"><span class="hljs-meta">@RunWith(PowerMockRunner.class)</span>
<span class="hljs-meta">@PrepareForTest({
    ExampleClass.class
})</span>
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">ExampleClassTest</span> </span>{

    <span class="hljs-keyword">private</span> ExampleClass classUnderTest;

    <span class="hljs-meta">@Before</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">setUp</span><span class="hljs-params">()</span> <span class="hljs-keyword">throws</span> Exception </span>{
        <span class="hljs-comment">// Create constructor of ExampleClass</span>
        classUnderTest = <span class="hljs-keyword">new</span> ExampleClass();
    }

    <span class="hljs-meta">@Test</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">getHeight_shoudReturnHeightOfView</span><span class="hljs-params">()</span> <span class="hljs-keyword">throws</span> NoSuchMethodException </span>{
        <span class="hljs-keyword">final</span> <span class="hljs-keyword">int</span> expectedHeight = <span class="hljs-number">100</span>;
        <span class="hljs-comment">// Given</span>
        <span class="hljs-keyword">final</span> CustomClass mckCustomClass = Mockito.mock(CustomClass.class);
        Mockito.when(mckCustomClass.getHeight()).theReturn(expectedHeight);
        // <span class="hljs-function">Make sure you match exact parameters <span class="hljs-keyword">while</span> <span class="hljs-title">mocking</span> <span class="hljs-params">(same as we <span class="hljs-keyword">do</span> <span class="hljs-keyword">for</span> Mockito.mock statements)</span>.
        <span class="hljs-comment">// There is also withArguments(first, second, ....)</span>
        <span class="hljs-comment">// and withAnyArguments() for cases when you dont care for arguments passed.</span>
        PowerMockito.<span class="hljs-title">whenNew</span><span class="hljs-params">(CustomClass.class)</span>.<span class="hljs-title">withNoArguments</span><span class="hljs-params">()</span>.<span class="hljs-title">thenReturn</span><span class="hljs-params">(mckCustomClass)</span></span>;

        <span class="hljs-keyword">final</span> <span class="hljs-keyword">int</span> actualResult = Whitebox.invokeMethod(classUnderTest, <span class="hljs-string">"getHeight"</span>);;

        Assert.assertEquals(expectedHeight, actualResult);
    }
}
</code></pre>
<blockquote>
<p>***Note: *** you should not call <code>invokeMethod()</code> unnecessarily, try to follow code execution flow to get to any private method.</p>
</blockquote>
<h3 id="heading-8-whiteboxsetinternalstate">8. Whitebox.setInternalState()</h3>
<p>PowerMockito allows you to inject value to globally declared member fields, this is also a wrapper around Java Reflection API's.</p>
<pre><code class="lang-Java">Whitebox.setInternalState(classUnderTest, <span class="hljs-string">"mCustomClassObject"</span>, (CustomClass) <span class="hljs-keyword">null</span>);
</code></pre>
<blockquote>
<p>***Note: *** You should not set values left and wright with <code>setInternalState()</code> method, this should only be used when there is some if condition that is always <code>true</code> and you need to test else condition. for e.x. a null check when that object cannot be null at that time.</p>
</blockquote>
<h3 id="heading-8-whiteboxgetinternalstate">8. Whitebox.getInternalState()</h3>
<p>Similar to <code>setInternalState()</code> you can get value of any global field at my time with <code>getInternalState()</code> method.</p>
<p>This method is really useful to test any void methods, we can get any state change caused by that void method and write our assertion on that.</p>
<p>for example:</p>
<pre><code class="lang-Java"><span class="hljs-comment">// Example Source Class</span>
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">ExampleClass</span> </span>{

    <span class="hljs-keyword">private</span> <span class="hljs-keyword">int</span> mHeight = <span class="hljs-number">0</span>;

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">clear</span><span class="hljs-params">()</span> </span>{
        <span class="hljs-comment">// this is a void method that updated height and does not return anything.</span>
        mHeight = <span class="hljs-number">0</span>;
    }
}
</code></pre>
<p>With method's like <code>clear()</code> that return void but change state of class, we can get value of <code>mHeight</code> and check if it was unset or not.</p>
<p>Here is how we would achieve that:</p>
<pre><code class="lang-Java"><span class="hljs-meta">@RunWith(PowerMockRunner.class)</span>
<span class="hljs-meta">@PrepareForTest({
    ExampleClass.class
})</span>
<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">ExampleClassTest</span> </span>{

    <span class="hljs-keyword">private</span> ExampleClass classUnderTest;

    <span class="hljs-meta">@Before</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">setUp</span><span class="hljs-params">()</span> <span class="hljs-keyword">throws</span> Exception </span>{
        <span class="hljs-comment">// Create constructor of ExampleClass</span>
        classUnderTest = <span class="hljs-keyword">new</span> ExampleClass();
    }

    <span class="hljs-meta">@Test</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">getHeight_shoudReturnHeightOfView</span><span class="hljs-params">()</span> <span class="hljs-keyword">throws</span> NoSuchMethodException </span>{
        <span class="hljs-comment">// Given</span>

        <span class="hljs-comment">// When</span>
        classUnderTest.clear()

        <span class="hljs-comment">// Then</span>
        <span class="hljs-keyword">final</span> <span class="hljs-keyword">int</span> mHeight = Whitebox.getInternalState(classUnderTest, <span class="hljs-string">"mHeight"</span>);;
        Assert.assertEquals(<span class="hljs-number">0</span>, mHeight);
    }
}
</code></pre>
]]></content:encoded></item><item><title><![CDATA[Mockito CheatSheet: Tldr and Tips]]></title><description><![CDATA[These are some of the useful methods and classes provided by Mockito
1. Mockito.mock()
Creates a mock of any class. By default, it will return default value for methods and fields when not mocked.
For Example:
Primitive data types such as byte, short...]]></description><link>https://blog.tejpratapsingh.com/mockito-cheatsheet-tldr-and-tips</link><guid isPermaLink="true">https://blog.tejpratapsingh.com/mockito-cheatsheet-tldr-and-tips</guid><category><![CDATA[Java]]></category><category><![CDATA[Testing]]></category><category><![CDATA[Android]]></category><category><![CDATA[mockito]]></category><category><![CDATA[Mocking]]></category><dc:creator><![CDATA[Tej Pratap Singh]]></dc:creator><pubDate>Wed, 12 Oct 2022 19:22:05 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/unsplash/tj7Bj_743JA/upload/v1665586569408/sAIVttsMX.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>These are some of the useful methods and classes provided by Mockito</p>
<h3 id="heading-1-mockitomock">1. Mockito.mock()</h3>
<p>Creates a mock of any class. By default, it will return default value for methods and fields when <strong><em>not</em></strong> mocked.</p>
<p>For Example:
Primitive data types such as <code>byte</code>, <code>short</code>, <code>int</code>, <code>long</code>, <code>float</code>, <code>double</code>, <code>boolean</code> and char will return default value i.e <code>0</code> or <code>false</code></p>
<p>Non-primitive data types such as <code>String</code>, <code>Arrays</code> and <code>Classes</code> return <code>null</code> when they are not mocked. </p>
<pre><code class="lang-java"><span class="hljs-comment">// with annotation</span>
<span class="hljs-meta">@Mock</span>
<span class="hljs-keyword">private</span> ClassName mock;

<span class="hljs-comment">// Or with static method</span>
<span class="hljs-keyword">final</span> ClassName mock = Mockito.mock(ClassName.class);

// mock methods that returns something
Mockito.when(mock.sampleMethod()).thenReturn(sampleVal);

// mock method to <span class="hljs-keyword">throw</span> Exception
Mockito.when(mock.sampleMethod()).thenThrow(SampleException.class);

// Mock <span class="hljs-keyword">void</span> methods
Mockito.doNothing().when(mock).method();

// you can get invocation parameters with .thenAnswer()
Mockito.when(mock.sampleMethod(Mockito.any(OtherClass.class))).thenAnswer((Answer&lt;ThirdClass&gt;) invocation -&gt; {
      <span class="hljs-keyword">final</span> OtherClass parameter1 = invocation.getArgument(<span class="hljs-number">0</span>);
      <span class="hljs-keyword">return</span> thirdClassObject; 
});

<span class="hljs-comment">// Verify interactions</span>
Mockito.verify(mock, Mockito.times(<span class="hljs-number">1</span>)).sampleMethod();

<span class="hljs-comment">// Verify, method should not be invoked even once</span>
Mockito.verify(mock, Mockito.never()).sampleMethod2();

<span class="hljs-comment">// Verify, no methods should be called on given mock</span>
Mockito.verifyNoMoreInteractions(otherMockedClass);
</code></pre>
<h3 id="heading-2-mockitospy">2. Mockito.spy()</h3>
<p>It is similar to <em><code>mock()</code></em> but instead of return default value it will call the actual implementation when <strong><em>not</em></strong> mocked.</p>
<pre><code class="lang-java"><span class="hljs-comment">// with annotation</span>
<span class="hljs-meta">@Spy</span>
<span class="hljs-keyword">private</span> ClassName spy;

<span class="hljs-comment">// Or with static method</span>
<span class="hljs-keyword">final</span> ClassName spy = Mockito.spy(ClassName.class);

// mock methods that returns something
Mockito.doReturn(value).when(spy).method();

// mock method to <span class="hljs-keyword">throw</span> exception
Mockito.doThrow(<span class="hljs-keyword">new</span> ExceptionClass()).when(spy).metohd();

<span class="hljs-comment">// mock void methods</span>
Mockito.doNothing().when(spy).method();
</code></pre>
<h3 id="heading-3-mockitomockstatic">3. Mockito.mockStatic()</h3>
<p>Now with Mockito 3, you can mock Classes with static methods.</p>
<pre><code class="lang-java"><span class="hljs-keyword">try</span> (MockedStatic&lt;Foo&gt; dummyStatic = Mockito.mockStatic(ClassName.class)) {
    dummyStatic.when(() -&gt; ClassName.method("param1"))
               .thenReturn("someValue");
    // when
    System.out.println(ClassName.method("param1"));
    //then
    dummyStatic.verify(
            () -&gt; ClassName.method("param1"),
            times(<span class="hljs-number">1</span>), 
    );
}
</code></pre>
<h3 id="heading-4-argumentmatcher">4. ArgumentMatcher</h3>
<p>Basic Rule to match any statement with Mockito is to correctly match its parameters. If any of the parameter did not match then instruction will not be mocked.</p>
<pre><code class="lang-java"><span class="hljs-comment">// example statement</span>
<span class="hljs-keyword">final</span> <span class="hljs-keyword">int</span> addition = calculator.getAddition(<span class="hljs-number">2</span>, <span class="hljs-number">3</span>);

<span class="hljs-comment">// you have to match exact parameters, in this case (2,3)</span>
Mockito.when(mckCalculator.getAddition(<span class="hljs-number">2</span>, <span class="hljs-number">3</span>)).thenReturn(<span class="hljs-number">5</span>);

<span class="hljs-comment">// If you mock for (3,4), you mocked result will not be returned</span>
Mockito.when(mckCalculator.getAddition(<span class="hljs-number">3</span>, <span class="hljs-number">4</span>)).thenReturn(<span class="hljs-number">5</span>);

<span class="hljs-comment">// For cases, where you do not know exact parameter then you can use Mockito.anyInt()</span>
Mockito.when(mckCalculator.getAddition(Mockito.anyInt(), Mockito.anyInt())).thenReturn(<span class="hljs-number">5</span>);
</code></pre>
<p>Similarly we have <code>Mockito.any()</code>, <code>Mockito.anyLong()</code>, <code>Mockito.anyString()</code>, <code>Mockito.anyBoolean()</code>, <code>Mockito.anyByte()</code>, <code>Mockito.anyChar()</code>, <code>Mockito.anyFloat()</code>, <code>Mockito.anyDouble()</code>, <code>Mockito.anyShort()</code>, <code>Mockito.anyList()</code>,  <code>Mockito.anySet()</code> and <code>Mockito.anyMap()</code></p>
<h3 id="heading-5-argumentcaptor">5. ArgumentCaptor</h3>
<p>You can also get value of parameters of mocked methods, you can then Assert for their value.</p>
<p>Below is the same example of calculator class.</p>
<pre><code class="lang-java"><span class="hljs-comment">// example statement</span>
<span class="hljs-keyword">final</span> <span class="hljs-keyword">int</span> addition = calculator.getAddition(<span class="hljs-number">2</span>, <span class="hljs-number">3</span>);

<span class="hljs-comment">// Create captor</span>
ArgumentCaptor&lt;Integer&gt; argumentCaptor = ArgumentCaptor.forClass(Integer.class);

Mockito.when(mckCalculator.getAddition(argumentCaptor.capture(), argumentCaptor.capture())).thenReturn(<span class="hljs-number">5</span>);

<span class="hljs-keyword">final</span> <span class="hljs-keyword">int</span> firstNum = argumentCaptor.getValue();
Assert.assertEquals(<span class="hljs-number">2</span>, firstNum);

<span class="hljs-comment">// You can get second num by calling getAllValues()</span>
<span class="hljs-keyword">final</span> <span class="hljs-keyword">int</span> secondNum = argumentCaptor.getAllValues()[<span class="hljs-number">1</span>];
Assert.assertEquals(<span class="hljs-number">3</span>, secondNum);
</code></pre>
]]></content:encoded></item><item><title><![CDATA[Android: Create PDF without any library [Part 3]]]></title><description><![CDATA[In  last part  we successfully created a complex Pdf with dynamic data.
After we create a Pdf, we should be able to show contents of Pdf to User, to do that we can use PdfRenderer class and get bitmap of every page inside Pdf.
Here is a simple functi...]]></description><link>https://blog.tejpratapsingh.com/android-create-pdf-without-any-library-part-3</link><guid isPermaLink="true">https://blog.tejpratapsingh.com/android-create-pdf-without-any-library-part-3</guid><category><![CDATA[Android]]></category><category><![CDATA[library]]></category><category><![CDATA[pdf]]></category><dc:creator><![CDATA[Tej Pratap Singh]]></dc:creator><pubDate>Fri, 24 Apr 2020 14:39:38 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1587738404895/duMUMwKHf.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>In  <a target='_blank' rel='noopener noreferrer'  href="https://blog.tejpratapsingh.com/android-create-pdf-without-any-library-part-2-ck9eads8g05e3css1bx1mlns2">last part</a>  we successfully created a complex Pdf with dynamic data.</p>
<p>After we create a Pdf, we should be able to show contents of Pdf to User, to do that we can use <code>PdfRenderer</code> class and get bitmap of every page inside Pdf.</p>
<p>Here is a simple function you can use to get Pdf pages as Bitmap</p>
<pre><code class="lang-java">  <span class="hljs-comment">/**
     * Convert PDF to bitmap, only works on devices above LOLLIPOP
     *
     * <span class="hljs-doctag">@param</span> pdfFile pdf file
     * <span class="hljs-doctag">@return</span> list of bitmap of every page
     * <span class="hljs-doctag">@throws</span> Exception
     */</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> ArrayList&lt;Bitmap&gt; <span class="hljs-title">pdfToBitmap</span><span class="hljs-params">(File pdfFile)</span> <span class="hljs-keyword">throws</span> Exception, IllegalStateException </span>{
        <span class="hljs-keyword">if</span> (pdfFile == <span class="hljs-keyword">null</span> || pdfFile.exists() == <span class="hljs-keyword">false</span>) {
            <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> IllegalStateException(<span class="hljs-string">""</span>);
        }
        <span class="hljs-keyword">if</span> (android.os.Build.VERSION.SDK_INT &lt; android.os.Build.VERSION_CODES.LOLLIPOP) {
            <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> Exception(<span class="hljs-string">"PDF preview image cannot be generated in this device"</span>);
        }
        <span class="hljs-keyword">if</span> (android.os.Build.VERSION.SDK_INT &lt; android.os.Build.VERSION_CODES.LOLLIPOP) {
            <span class="hljs-keyword">return</span> <span class="hljs-keyword">null</span>;
        }

        ArrayList&lt;Bitmap&gt; bitmaps = <span class="hljs-keyword">new</span> ArrayList&lt;&gt;();

        <span class="hljs-keyword">try</span> {
            PdfRenderer renderer = <span class="hljs-keyword">new</span> PdfRenderer(ParcelFileDescriptor.open(pdfFile, ParcelFileDescriptor.MODE_READ_ONLY));

            Bitmap bitmap;
            <span class="hljs-keyword">final</span> <span class="hljs-keyword">int</span> pageCount = renderer.getPageCount();
            <span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> i = <span class="hljs-number">0</span>; i &lt; pageCount; i++) {
                PdfRenderer.Page page = renderer.openPage(i);

                <span class="hljs-keyword">int</span> width = page.getWidth();
                <span class="hljs-keyword">int</span> height = page.getHeight();

                <span class="hljs-comment">/* FOR HIGHER QUALITY IMAGES, USE:
                int width = context.getResources().getDisplayMetrics().densityDpi / 72 * page.getWidth();
                int height = context.getResources().getDisplayMetrics().densityDpi / 72 * page.getHeight();
                */</span>

                bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
                page.render(bitmap, <span class="hljs-keyword">null</span>, <span class="hljs-keyword">null</span>, PdfRenderer.Page.RENDER_MODE_FOR_DISPLAY);

                bitmaps.add(bitmap);

                <span class="hljs-comment">// close the page</span>
                page.close();
            }
            <span class="hljs-comment">// close the renderer</span>
            renderer.close();
        } <span class="hljs-keyword">catch</span> (Exception ex) {
            ex.printStackTrace();
        }
        <span class="hljs-keyword">return</span> bitmaps;
    }
</code></pre>
<hr>
<p>To make your work easier i have created a Library to generate dynamic PDF using above methods <a target='_blank' rel='noopener noreferrer'  href="https://github.com/tejpratap46/PDFCreatorAndroid">View on Github</a></p>
<p> <a target='_blank' rel='noopener noreferrer'  href="https://github.com/tejpratap46/PDFCreatorAndroid"><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1587719632043/mXw6_IETk.png" alt="Simple library to generate and view PDF in Android.png"></a> </p>
]]></content:encoded></item><item><title><![CDATA[Android: Create PDF without any library [Part 2]]]></title><description><![CDATA[In  last part  we created a static PDF in Android.
But creating PDF from static data has a big disadvantage. You cannot set data at runtime, i.e. you cannot set text from DB or load image from internet.
Creating PDF: Advanced
To solve this problem:

...]]></description><link>https://blog.tejpratapsingh.com/android-create-pdf-without-any-library-part-2</link><guid isPermaLink="true">https://blog.tejpratapsingh.com/android-create-pdf-without-any-library-part-2</guid><category><![CDATA[Android]]></category><category><![CDATA[pdf]]></category><category><![CDATA[library]]></category><dc:creator><![CDATA[Tej Pratap Singh]]></dc:creator><pubDate>Fri, 24 Apr 2020 14:24:48 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1587722622869/EavEZJ8qo.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>In  <a target='_blank' rel='noopener noreferrer'  href="https://blog.tejpratapsingh.com/android-create-pdf-without-any-library-ck9dz0vdg05agcxs14l1ix0rg">last part</a>  we created a static PDF in Android.</p>
<p>But creating PDF from static data has a big disadvantage. You cannot set data at runtime, i.e. you cannot set text from DB or load image from internet.</p>
<h4 id="creating-pdf-advanced">Creating PDF: Advanced</h4>
<p>To solve this problem:</p>
<ul>
<li>We will create empty Activity with <code>LinearLayout</code> of size <strong>[595xwrap_content]</strong>, we will get reference of that <code>LinearLayout</code> and Add our Views programmatically.</li>
<li>We only need above LinearLayout so we can calculate height of views we are about to add. As <code>View</code>s 
created programmatically cannot give height they will take after rendering. i.e. rendering of each <code>View</code> is mandatory.</li>
<li>Now we know why we need to first render <code>View</code> to layout, let&#39;s proceed:</li>
<li>Let&#39;s sat we need to add a <code>TextView</code> to Pdf, we will call it &#39;textView1&#39;.</li>
<li>&#39;textView1&#39; will be added to <strong>595xwrap_content</strong> <code>LinearLayout</code>, So it can render and we take a note of its height.</li>
</ul>
<pre><code class="lang-java"><span class="hljs-keyword">private</span> <span class="hljs-keyword">final</span> Map&lt;String, <span class="hljs-keyword">int</span>&gt; viewToHeightMap = <span class="hljs-keyword">new</span> HashMap&lt;&gt;();

<span class="hljs-keyword">final</span> LinearLayout layout595xwrap_content = findViewById(R.id.layout595xwrap_content);

<span class="hljs-keyword">final</span> TextView textView1 = <span class="hljs-keyword">new</span> TextView(context);
layout595xwrap_content.add(textView1);
textView1.post(<span class="hljs-keyword">new</span> Runnable() {
  <span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">run</span><span class="hljs-params">()</span> </span>{
    layout595xwrap_content.put(<span class="hljs-string">'textView1'</span>, textView1.getHeight())
  }
})
</code></pre>
<ul>
<li>Accordingly add all view to <strong>595xwrap_content</strong> <code>LinearLayout</code> one-by-one and take a note of height of each view.</li>
<li>Create <code>LinearLayout</code> of size <strong>595x842px</strong> which will be Single Page in Pdf. Add Views one-by-one until height sum reaches 842px.</li>
<li>When 842px height is reached, again create new LinearLayout of size <strong>595x842px</strong> which will be Second Page in the Pdf and so on.</li>
<li>After you have create List of <code>LineatLayout</code>s as Pdf Pages, we simply have to  <a target='_blank' rel='noopener noreferrer'  href="https://blog.tejpratapsingh.com/android-create-pdf-without-any-library-ck9dz0vdg05agcxs14l1ix0rg">use methods</a>  in previous part to generate Pdf.</li>
</ul>
<p>In  <a target='_blank' rel='noopener noreferrer'  href="https://blog.tejpratapsingh.com/android-create-pdf-without-any-library-part-3-ck9eawv4u05edcss1ftdwo5po">Next Part</a>  we will generate preview of any Pdf File using <code>PdfRenderer</code></p>
<hr>
<p>To make your work easier i have created a Library to generate dynamic PDF using above methods <a target='_blank' rel='noopener noreferrer'  href="https://github.com/tejpratap46/PDFCreatorAndroid">View on Github</a></p>
<p> <a target='_blank' rel='noopener noreferrer'  href="https://github.com/tejpratap46/PDFCreatorAndroid"><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1587719632043/mXw6_IETk.png" alt="Simple library to generate and view PDF in Android.png"></a> </p>
]]></content:encoded></item><item><title><![CDATA[Android: Create PDF without any library [Part 1]]]></title><description><![CDATA[PDF are simple document format with supports text and images. It is simple to share, non editable can be password protected. Great for receipts and invoices.
As i was looking for a library to create PDF natively on Android but couldn't found one that...]]></description><link>https://blog.tejpratapsingh.com/android-create-pdf-without-any-library-part-1</link><guid isPermaLink="true">https://blog.tejpratapsingh.com/android-create-pdf-without-any-library-part-1</guid><category><![CDATA[Android]]></category><category><![CDATA[pdf]]></category><category><![CDATA[library]]></category><dc:creator><![CDATA[Tej Pratap Singh]]></dc:creator><pubDate>Fri, 24 Apr 2020 09:06:50 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1587720181054/iwHraH2sJ.png" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p><a target='_blank' rel='noopener noreferrer'  href="https://en.wikipedia.org/wiki/PDF">PDF</a> are simple document format with supports text and images. It is simple to share, non editable can be password protected. Great for receipts and invoices.</p>
<p>As i was looking for a library to create PDF natively on Android but couldn&#39;t found one that is free to use.</p>
<p>Some time ago, i had a use case where i needed to create PDF on device and unfortunately no free to use library was available at that time which can create PDF&#39;s on user&#39;s device.</p>
<p>So, i digged into Android&#39;s  <a target='_blank' rel='noopener noreferrer'  href="https://developer.android.com/training/printing/custom-docs.html">Printing custom documents</a> where i came across  <a target='_blank' rel='noopener noreferrer'  href="https://developer.android.com/reference/android/graphics/pdf/PdfDocument">PdfDocument</a> which can generate PDF from <code>View</code>.</p>
<p>Here is how it is done:</p>
<ol>
<li><p>We start by creating a PdfDocument</p>
<pre><code class="lang-java"><span class="hljs-comment">// Create PDF Document.</span>
PdfDocument pdfDocument = <span class="hljs-keyword">new</span> PdfDocument();
</code></pre>
</li>
<li><p>Create a Page in PdfDocument</p>
<pre><code class="lang-java">PdfDocument.PageInfo pageInfo = <span class="hljs-keyword">new</span> PdfDocument.PageInfo.
                     Builder((<span class="hljs-keyword">int</span>) PDF_PAGE_WIDTH, (<span class="hljs-keyword">int</span>) PDF_PAGE_HEIGHT, i + <span class="hljs-number">1</span>).create();
</code></pre>
</li>
<li><p>Create a view to be printed on PDF</p>
<pre><code class="lang-java">TextView view = <span class="hljs-keyword">new</span> TextView(context);
view.setText(<span class="hljs-string">"PDF Example"</span>);
</code></pre>
</li>
<li><p>Draw view on the page</p>
<pre><code class="lang-java">Canvas pageCanvas = page.getCanvas();
pageCanvas.scale(<span class="hljs-number">1f</span>, <span class="hljs-number">1f</span>);
<span class="hljs-keyword">int</span> pageWidth = pageCanvas.getWidth();
<span class="hljs-keyword">int</span> pageHeight = pageCanvas.getHeight();
<span class="hljs-keyword">int</span> measureWidth = View.MeasureSpec.makeMeasureSpec(pageWidth, View.MeasureSpec.EXACTLY);
<span class="hljs-keyword">int</span> measuredHeight = View.MeasureSpec.makeMeasureSpec(pageHeight, View.MeasureSpec.EXACTLY);
contentView.measure(measureWidth, measuredHeight);
contentView.layout(<span class="hljs-number">0</span>, <span class="hljs-number">0</span>, pageWidth, pageHeight);
contentView.draw(pageCanvas);
</code></pre>
</li>
<li><p>Finish the page</p>
<pre><code class="lang-java">pdfDocument.finishPage(page);
</code></pre>
</li>
<li><p>Save pdf to file</p>
<pre><code class="lang-java">File pdfFile = <span class="hljs-keyword">new</span> File(mFilePath);
<span class="hljs-comment">// Write PDFDocument to the file.</span>
FileOutputStream  fos = <span class="hljs-keyword">new</span> FileOutputStream(pdfFile);
pdfDocument.writeTo(fos);
<span class="hljs-comment">// Close output stream</span>
fos.close();
<span class="hljs-comment">// close the document</span>
pdfDocument.close();
</code></pre>
</li>
</ol>
<p>Above code will create a simple PDF with one page that contains TextView inside it.</p>
<hr>
<p>Now let&#39;s start creating an actual PDF...</p>
<h4 id="creating-pdf-simple">Creating PDF: Simple</h4>
<p>PdfDocument API will renders any views to PDF. It is as simple as creating an activity, getting its <code>view</code> and rendering PdfDocument of that view.</p>
<blockquote>
<p><em>A Simple PDF page is of <code>height=&quot;842px&quot;</code> and <code>width=&quot;595px&quot;</code></em></p>
<p><em>Note: As dp and sp are device dependent, make sure you create all of your layout in px as it will look same in all devices.</em></p>
</blockquote>
<p>Steps:</p>
<ol>
<li>Create an <code>Activity</code> which will have a vertical <code>LinearLayout</code> with <code>height=&quot;842px&quot;</code> and <code>width=&quot;595px&quot;</code>.</li>
<li>Add all views with static data inside it.</li>
<li>Make sure no view exceeds allotted height as it will be trimmed.</li>
<li>If you want to create new page just repeat 1-3.</li>
<li>In your <code>onCreate()</code>, get reference of all <code>LinearLayout</code> and create PDF (using step 4) with each layout as one page.</li>
<li>Done.</li>
</ol>
<p>P.S. in  <a target='_blank' rel='noopener noreferrer'  href="https://blog.tejpratapsingh.com/android-create-pdf-without-any-library-part-2-ck9eads8g05e3css1bx1mlns2">next chapter</a>  we will create more advanced PDF and dynamically insert data and create multi page PDF</p>
<hr>
<p>To make your work easier i have created a Library to generate dynamic PDF using above methods <a target='_blank' rel='noopener noreferrer'  href="https://github.com/tejpratap46/PDFCreatorAndroid">View on Github</a></p>
<p> <a target='_blank' rel='noopener noreferrer'  href="https://github.com/tejpratap46/PDFCreatorAndroid"><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1587719632043/mXw6_IETk.png" alt="Simple library to generate and view PDF in Android.png"></a> </p>
]]></content:encoded></item><item><title><![CDATA[Create your own Event Emitter in JS]]></title><description><![CDATA[In my  previous post, i wrote about how we can design you app using Observer Pattern.
Now we will try something simpler and which works across our application and not bound to a Object.
It has some interesting use cases like listening to Route Change...]]></description><link>https://blog.tejpratapsingh.com/create-your-own-event-emitter-in-js</link><guid isPermaLink="true">https://blog.tejpratapsingh.com/create-your-own-event-emitter-in-js</guid><category><![CDATA[JavaScript]]></category><category><![CDATA[Web Development]]></category><category><![CDATA[RxJS]]></category><dc:creator><![CDATA[Tej Pratap Singh]]></dc:creator><pubDate>Fri, 01 Nov 2019 16:26:40 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1572625394242/TMh8MKvQ1.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>In my  <a target='_blank' rel='noopener noreferrer'  href="https://blog.tejpratapsingh.com/rxjs-at-its-basic-ck1mqannv00e68zs1f5qixkzj">previous post</a>, i wrote about how we can design you app using Observer Pattern.</p>
<p>Now we will try something simpler and which works across our application and not bound to a <code>Object</code>.</p>
<p>It has some interesting use cases like listening to Route Change so you can change page header and show logged in user info Or listening an event when next page is loaded.</p>
<p>Event emitter can be achieved with 3 simple steps:</p>
<ol>
<li>Register event</li>
<li>Trigger event</li>
<li>Unregister that event</li>
</ol>
<hr>
<p>So, let&#39;s Start:</p>
<h3 id="initialisation">Initialisation</h3>
<p>First thing first, we need a global variable to hold all events and their callbacks like this:</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// events property will hold our events and all the listeners it has.</span>
<span class="hljs-keyword">this</span>.events = {};
</code></pre>
<p>And if you are using ES6 classes, we have to declare this class as singleton, to do that we simply create a global variable and check if variable is initialised or not.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> eventManagerInstance = <span class="hljs-literal">null</span>;
<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">EventManager</span> </span>{
  <span class="hljs-keyword">constructor</span>() {
    <span class="hljs-keyword">if</span> (!eventManagerInstance) {
      <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"event inttialised"</span>);
      eventManagerInstance = <span class="hljs-keyword">this</span>;
      <span class="hljs-comment">// events hold our events and their callbacks</span>
      <span class="hljs-keyword">this</span>.events = {};
      <span class="hljs-comment">// eventTypes can be used to keep track of all the events that can be used by this event manager.</span>
      <span class="hljs-keyword">this</span>.eventTypes = {
        ROUTE_CHANGED: <span class="hljs-string">"changeRoute"</span>,
        SCROLL_DIRECTION_CHANGED: <span class="hljs-string">"scrollDirectionChanged"</span>,
        SCROLL_LOAD_NEXT_PAGE: <span class="hljs-string">"scrollLoadNextPage"</span>
      };
    }
    <span class="hljs-keyword">return</span> eventManagerInstance;
  }
}
</code></pre>
<h3 id="register-event-in-event-manager">Register event in Event Manager</h3>
<p>To register a event we need 2 parameters, a unique name for event and a callback function.</p>
<pre><code class="lang-javascript">
<span class="hljs-comment">/**
   * Register to a event
   *
   * @param {string} eventName Name of event to register for
   * @param {Function} fn callback function
   */</span>
  on(eventName, fn) {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"event On: "</span> + eventName);
    <span class="hljs-keyword">this</span>.events[eventName] = <span class="hljs-keyword">this</span>.events[eventName] || [];
    <span class="hljs-keyword">this</span>.events[eventName].push(fn);
  }
</code></pre>
<h3 id="trigger-that-event">Trigger that event</h3>
<p>After we set up a event listener we can send data via triggers like this,</p>
<pre><code class="lang-javascript"><span class="hljs-comment">/**
   * Trigger a event with data
   *
   * @param {string} eventName Event to call
   * @param {Object} data optional data to pass
   */</span>
  trigger(eventName, data) {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"event triggered: "</span> + eventName);
    <span class="hljs-keyword">if</span> (<span class="hljs-keyword">this</span>.events[eventName]) {
      <span class="hljs-keyword">this</span>.events[eventName].forEach(<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">fn</span>) </span>{
        fn(data);
      });
    }
  }
</code></pre>
<h3 id="unregister-that-event">Unregister that event</h3>
<p>Once we are done listening to a particular event we should be able to unregister.</p>
<pre><code class="lang-javascript">  <span class="hljs-comment">/**
   * Un-Register from a event
   *
   * @param {string} eventName Name of event to de-register from
   * @param {Function} fn callback function to be removed
   */</span>
  off(eventName, fn) {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"event Off: "</span> + eventName);
    <span class="hljs-keyword">if</span> (<span class="hljs-keyword">this</span>.events[eventName]) {
      <span class="hljs-keyword">for</span> (<span class="hljs-keyword">var</span> i = <span class="hljs-number">0</span>; i &lt; <span class="hljs-keyword">this</span>.events[eventName].length; i++) {
        <span class="hljs-keyword">if</span> (<span class="hljs-keyword">this</span>.events[eventName][i] === fn) {
          <span class="hljs-keyword">this</span>.events[eventName].splice(i, <span class="hljs-number">1</span>);
          <span class="hljs-keyword">break</span>;
        }
      }
    }
  }
</code></pre>
<hr>
<p>Here is the full implementation of Event Manager class.</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// This class is implemented as SINGLETON(singleton)</span>
<span class="hljs-keyword">let</span> eventManagerInstance = <span class="hljs-literal">null</span>;

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">EventManager</span> </span>{
  <span class="hljs-keyword">constructor</span>() {
    <span class="hljs-keyword">if</span> (!eventManagerInstance) {
      <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"event inttialised"</span>);
      eventManagerInstance = <span class="hljs-keyword">this</span>;
      <span class="hljs-keyword">this</span>.events = {};
      <span class="hljs-keyword">this</span>.eventTypes = {
        ROUTE_CHANGED: <span class="hljs-string">"changeRoute"</span>,
        SCROLL_DIRECTION_CHANGED: <span class="hljs-string">"scrollDirectionChanged"</span>,
        SCROLL_LOAD_NEXT_PAGE: <span class="hljs-string">"scrollLoadNextPage"</span>
      };
    }
    <span class="hljs-keyword">return</span> eventManagerInstance;
  }

  <span class="hljs-comment">/**
   * Register to a event
   *
   * @param {string} eventName Name of event to register for
   * @param {Function} fn callback function
   */</span>
  on(eventName, fn) {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"event On: "</span> + eventName);
    <span class="hljs-keyword">this</span>.events[eventName] = <span class="hljs-keyword">this</span>.events[eventName] || [];
    <span class="hljs-keyword">this</span>.events[eventName].push(fn);
  }

  <span class="hljs-comment">/**
   * Un-Register from a event
   *
   * @param {string} eventName Name of event to de-register from
   * @param {Function} fn callback function to be removed
   */</span>
  off(eventName, fn) {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"event Off: "</span> + eventName);
    <span class="hljs-keyword">if</span> (<span class="hljs-keyword">this</span>.events[eventName]) {
      <span class="hljs-keyword">for</span> (<span class="hljs-keyword">var</span> i = <span class="hljs-number">0</span>; i &lt; <span class="hljs-keyword">this</span>.events[eventName].length; i++) {
        <span class="hljs-keyword">if</span> (<span class="hljs-keyword">this</span>.events[eventName][i] === fn) {
          <span class="hljs-keyword">this</span>.events[eventName].splice(i, <span class="hljs-number">1</span>);
          <span class="hljs-keyword">break</span>;
        }
      }
    }
  }

  <span class="hljs-comment">/**
   * Trigger a event with data
   *
   * @param {string} eventName Event to call
   * @param {Object} data optional data to pass
   */</span>
  trigger(eventName, data) {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"event triggered: "</span> + eventName);
    <span class="hljs-keyword">if</span> (<span class="hljs-keyword">this</span>.events[eventName]) {
      <span class="hljs-keyword">this</span>.events[eventName].forEach(<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">fn</span>) </span>{
        fn(data);
      });
    }
  }
}
</code></pre>
<hr>
<h3 id="how-to-use-eventmanager-class">How to use EventManager class</h3>
<p>Using event manager is simple, you just have to subscribe to a event like this:</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Get eventManager instance</span>
<span class="hljs-keyword">this</span>.eventManager = <span class="hljs-keyword">new</span> EventManager();

<span class="hljs-comment">// Declare Event Callback Function, so we can unregister it as sometime.</span>
<span class="hljs-keyword">this</span>.eventCallbackhandler = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">eventData</span>) </span>{
  <span class="hljs-built_in">console</span>.log(eventData);
};

<span class="hljs-comment">// Subscribe to ROUTE_CHANGED event</span>
<span class="hljs-keyword">this</span>.eventManager.on(
  <span class="hljs-keyword">this</span>.eventManager.eventTypes.ROUTE_CHANGED,
  <span class="hljs-keyword">this</span>.eventCallbackhandler
);
</code></pre>
<p>To Trigger ROUTE_CHANGED from different component, we just have to</p>
<pre><code class="lang-javascript">emitEvent() {
  <span class="hljs-keyword">const</span> eventManager = <span class="hljs-keyword">new</span> EventManager();
  eventManager.trigger(eventManager.eventTypes.ROUTE_CHANGED, {
    eventSource: <span class="hljs-string">"EventEmitterComponent"</span>
  });
}
</code></pre>
<hr>
<p>Here is a working sample on  <a target='_blank' rel='noopener noreferrer'  href="https://codesandbox.io/s/js-event-manager-xnimu">codesandbox.io</a> </p>
<div class="embed-wrapper"><div class="embed-loading"><div class="loadingRow"></div><div class="loadingRow"></div></div><a class="embed-card" data-card-width="600px" data-card-key="2e4d628b39a64b99917c73956a16b477" href="https://codesandbox.io/embed/js-event-manager-xnimu?fontsize=14" data-card-controls="0" data-card-theme="light">https://codesandbox.io/embed/js-event-manager-xnimu?fontsize=14</a></div>
]]></content:encoded></item><item><title><![CDATA[Observer Pattern In JS (RxJS at its basic)]]></title><description><![CDATA[ReactiveX or Reactive Extensions
 RxJS  is javascript implementation of Reactive Extension, it allows you to use  Observer pattern  in your web app.

RxJS is much more than what we are going to learn here, that is why the name (RxJS at its basic)

At...]]></description><link>https://blog.tejpratapsingh.com/observer-pattern-in-js-rxjs-at-its-basic</link><guid isPermaLink="true">https://blog.tejpratapsingh.com/observer-pattern-in-js-rxjs-at-its-basic</guid><category><![CDATA[RxJS]]></category><category><![CDATA[Reactive Programming]]></category><category><![CDATA[JavaScript]]></category><dc:creator><![CDATA[Tej Pratap Singh]]></dc:creator><pubDate>Fri, 11 Oct 2019 22:54:47 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1570828477657/oNyo6MnDn.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h2 id="reactivex-or-reactive-extensions">ReactiveX or Reactive Extensions</h2>
<p> <a target='_blank' rel='noopener noreferrer'  href="https://github.com/ReactiveX/rxjs">RxJS</a>  is javascript implementation of Reactive Extension, it allows you to use  <a target='_blank' rel='noopener noreferrer'  href="https://en.wikipedia.org/wiki/Observer_pattern">Observer pattern</a>  in your web app.</p>
<blockquote>
<p>RxJS is much more than what we are going to learn here, that is why the name <strong>(RxJS at its basic)</strong></p>
</blockquote>
<p>At its basic Observer pattern lets you <em>subscribe</em> to changes in <em>subject</em> with the help of <em>events</em>.</p>
<p>First we will focus on <code>Subscribers</code> and <code>Events</code>:</p>
<h3 id="subscriber-">Subscriber:</h3>
<p>Object has a property named <code>subscribers</code> to manage subscribers who want to listen to changes in our <code>subject</code>.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> subscribers= []
</code></pre>
<p>When a subscriber arrives, object adds it to <code>subscribers</code> and when a subscriber wants to unsubscribe, subject should remove subscriber from his <code>subscribers</code></p>
<h3 id="event-">Event:</h3>
<p>When data of <code>subject</code> is changed or when <code>subject</code> wants to inform changes to its subscribers it triggers an event. When an event is triggered, it is duty of a subject to inform every subscriber about the event. To do that we just have to iterate over all subscribers and execute their callbacks.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">this</span>.subscribers.forEach(<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">fn</span>) </span>{
  fn(data);
});
</code></pre>
<p>So let&#39;s come to the final step of a Observable Pattern and that is <code>Subject</code></p>
<h3 id="subject-">Subject:</h3>
<p>A subject which just an Object which informs its changes to all of its subscribers.</p>
<p>Here is an example of a general Observable Subject will extend.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">ObservableSubject</span> </span>{
  <span class="hljs-keyword">constructor</span>() {
    <span class="hljs-keyword">this</span>.subscribers = [];
  }

  getAllSubscribers() {
    <span class="hljs-keyword">return</span> <span class="hljs-keyword">this</span>.subscribers;
  }

  <span class="hljs-comment">/**
   * Register to a event
   *
   * @param {Function} fn subscriber callback function
   */</span>
  subscribe(fn) {
    <span class="hljs-keyword">this</span>.subscribers.push(fn);
  }

  <span class="hljs-comment">/**
   * Un-Register from a event
   *
   * @param {Function} fn callback function to be removed
   */</span>
  unsubscribe(eventName, fn) {
    <span class="hljs-keyword">if</span> (<span class="hljs-keyword">this</span>.subscribers) {
      <span class="hljs-keyword">for</span> (<span class="hljs-keyword">var</span> i = <span class="hljs-number">0</span>; i &lt; <span class="hljs-keyword">this</span>.subscribers.length; i++) {
        <span class="hljs-keyword">if</span> (<span class="hljs-keyword">this</span>.subscribers[i] === fn) {
          <span class="hljs-keyword">this</span>.subscribers.splice(i, <span class="hljs-number">1</span>);
          <span class="hljs-keyword">break</span>;
        }
      }
    }
  }

  <span class="hljs-comment">/**
   * Trigger a event with data
   *
   * @param {Object} data optional data to pass
   */</span>
  trigger(data) {
    <span class="hljs-keyword">if</span> (<span class="hljs-keyword">this</span>.subscribers) {
      <span class="hljs-keyword">this</span>.subscribers.forEach(<span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">fn</span>) </span>{
        fn(data);
      });
    }
  }
}
</code></pre>
<p>So, let&#39;s make a observable User which will extent <code>ObservableSubject</code></p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> ObservableSubject <span class="hljs-keyword">from</span> <span class="hljs-string">"./ObservableSubject"</span>;

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">User</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">ObservableSubject</span> </span>{
  setName(name) {
    <span class="hljs-keyword">this</span>.name = name;
    <span class="hljs-keyword">this</span>.trigger({
      user: {
        name: <span class="hljs-keyword">this</span>.name,
        email: <span class="hljs-keyword">this</span>.email
      }
    });
  }

  getName() {
    <span class="hljs-keyword">return</span> <span class="hljs-keyword">this</span>.name;
  }

  setEmail(email) {
    <span class="hljs-keyword">this</span>.email = email;
    <span class="hljs-keyword">this</span>.trigger({
      user: {
        name: <span class="hljs-keyword">this</span>.name,
        email: <span class="hljs-keyword">this</span>.email
      }
    });
  }

  getEmail() {
    <span class="hljs-keyword">return</span> <span class="hljs-keyword">this</span>.email;
  }
}
</code></pre>
<p>And this concludes a basic RxJs implementation.</p>
<p>Complete example is over at  <a target='_blank' rel='noopener noreferrer'  href="https://codesandbox.io/s/js-event-observer-bvjdd">codesandbox</a> </p>
<div class="embed-wrapper"><div class="embed-loading"><div class="loadingRow"></div><div class="loadingRow"></div></div><a class="embed-card" data-card-width="600px" data-card-key="2e4d628b39a64b99917c73956a16b477" href="https://codesandbox.io/embed/js-event-observer-bvjdd?autoresize=1&expanddevtools=1&fontsize=14&hidenavigation=1&module=%2Fsrc%2FObservableSubject.js" data-card-controls="0" data-card-theme="light">https://codesandbox.io/embed/js-event-observer-bvjdd?autoresize=1&expanddevtools=1&fontsize=14&hidenavigation=1&module=%2Fsrc%2FObservableSubject.js</a></div>
]]></content:encoded></item><item><title><![CDATA[Creating a Simple Router for you web app]]></title><description><![CDATA[Routing:

Routing is the process of selecting a path for traffic in a network or between or across multiple networks.

Im pretty sure that you all know what Router is and what it does. But, how to make one?
It's 4 basic steps:

Add click handler to e...]]></description><link>https://blog.tejpratapsingh.com/creating-a-simple-router-for-you-web-app</link><guid isPermaLink="true">https://blog.tejpratapsingh.com/creating-a-simple-router-for-you-web-app</guid><category><![CDATA[router]]></category><category><![CDATA[JavaScript]]></category><dc:creator><![CDATA[Tej Pratap Singh]]></dc:creator><pubDate>Wed, 09 Oct 2019 19:27:11 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1570822829802/vKB56F6-o.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h3 id="routing-">Routing:</h3>
<blockquote>
<p>Routing is the process of selecting a path for traffic in a network or between or across multiple networks.</p>
</blockquote>
<p>Im pretty sure that you all know what Router is and what it does. But, how to make one?</p>
<p>It&#39;s 4 basic steps:</p>
<ul>
<li><p>Add click handler to every anchor tag <code>&lt;a&gt;</code></p>
<pre><code class="lang-javascript"><span class="hljs-built_in">document</span>.addEventListener(
      <span class="hljs-string">"click"</span>,
      <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">event</span>) </span>{
        <span class="hljs-keyword">if</span> (event.target.tagName === <span class="hljs-string">"A"</span>) {
          event.preventDefault();
          <span class="hljs-keyword">var</span> href = event.target.href;
          <span class="hljs-built_in">console</span>.log(href);
        }
}, <span class="hljs-literal">false</span>);
</code></pre>
</li>
<li><p>On click handler, make get request to <code>href</code> of <code>&lt;a&gt;</code> and load html to current page.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">var</span> xhr = <span class="hljs-keyword">new</span> XMLHttpRequest();
xhr.onreadystatechange = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>{
<span class="hljs-keyword">if</span> (xhr.readyState === XMLHttpRequest.DONE) {
  history.pushState([], href, href);
  <span class="hljs-comment">// Here we are replacing current page html using new page html</span>
  <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">"app"</span>).innerHTML = xhr.responseText;
}
};
xhr.open(<span class="hljs-string">"GET"</span>, href, <span class="hljs-literal">true</span>);
xhr.send(<span class="hljs-literal">null</span>);
</code></pre>
</li>
<li><p>Push new page to <a target='_blank' rel='noopener noreferrer'  href="https://developer.mozilla.org/en-US/docs/Web/API/Window/history">history</a></p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Add new history entry</span>
history.pushState([], title, href);
</code></pre>
</li>
<li>Add a navigation handler to know when user pressed back and forward on browser.<pre><code class="lang-javascript"><span class="hljs-comment">// Listen to browser history event</span>
<span class="hljs-built_in">window</span>.addEventListener(<span class="hljs-string">"popstate"</span>, <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">e</span>) </span>{
<span class="hljs-comment">// Download new page's html and set it to current page </span>
<span class="hljs-keyword">var</span> xhr = <span class="hljs-keyword">new</span> XMLHttpRequest();
xhr.onreadystatechange = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">if</span> (xhr.readyState === XMLHttpRequest.DONE) {
    <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">"app"</span>).innerHTML = xhr.responseText;
  }
};
xhr.open(<span class="hljs-string">"GET"</span>, <span class="hljs-built_in">window</span>.location.pathname, <span class="hljs-literal">true</span>);
xhr.send(<span class="hljs-literal">null</span>);
});
</code></pre>
</li>
</ul>
<p>Here is code sample on <a target='_blank' rel='noopener noreferrer'  href="https://swhhe.csb.app/" title="(target|_blank)">codesandbox</a></p>
<div class="embed-wrapper"><div class="embed-loading"><div class="loadingRow"></div><div class="loadingRow"></div></div><a class="embed-card" data-card-width="600px" data-card-key="2e4d628b39a64b99917c73956a16b477" href="https://codesandbox.io/embed/simple-router-example-swhhe?fontsize=14" data-card-controls="0" data-card-theme="light">https://codesandbox.io/embed/simple-router-example-swhhe?fontsize=14</a></div>
<p>Above example can easily be implemented as a <code>&lt;Link/&gt;</code> Component in react.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">import</span> React, { Component } <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Link</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Component</span> </span>{

    <span class="hljs-keyword">constructor</span>(props) {
        <span class="hljs-keyword">super</span>(props);
        <span class="hljs-keyword">this</span>.state = props;

        <span class="hljs-keyword">this</span>.linkClicked = <span class="hljs-keyword">this</span>.linkClicked.bind(<span class="hljs-keyword">this</span>);
    }

    componentWillReceiveProps(nextProps) {
        <span class="hljs-comment">// You don't have to do this check first, but it can help prevent an unneeded render</span>
        <span class="hljs-keyword">if</span> (nextProps.href !== <span class="hljs-keyword">this</span>.state.href) {
            <span class="hljs-keyword">this</span>.setState({ href: nextProps.href });
        }
        <span class="hljs-keyword">if</span> (nextProps.title !== <span class="hljs-keyword">this</span>.state.title) {
            <span class="hljs-keyword">this</span>.setState({ title: nextProps.title });
        }
    }

    linkClicked(event) {
        <span class="hljs-keyword">if</span> (!<span class="hljs-keyword">this</span>.state.href || <span class="hljs-keyword">this</span>.state.href.length &lt;= <span class="hljs-number">0</span>) {
            event.preventDefault();
            <span class="hljs-keyword">return</span> <span class="hljs-literal">false</span>;
        }
        <span class="hljs-keyword">if</span> (<span class="hljs-keyword">typeof</span> <span class="hljs-built_in">window</span> != <span class="hljs-string">'undefined'</span>) {
            event.preventDefault();
            history.pushState(<span class="hljs-keyword">this</span>.state.title, <span class="hljs-keyword">this</span>.state.title, <span class="hljs-keyword">this</span>.state.href);
            <span class="hljs-built_in">window</span>.title = <span class="hljs-keyword">this</span>.state.title;
            history.pushState([], <span class="hljs-keyword">this</span>.state.href, <span class="hljs-keyword">this</span>.state.href);
            <span class="hljs-comment">// Here we are replacing current page html using new page html</span>
            <span class="hljs-comment">// Set new state for your component here</span>
        }
    }

    render() {
        <span class="hljs-keyword">return</span> (
            <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">a</span> <span class="hljs-attr">href</span>=<span class="hljs-string">{this.state.href}</span> <span class="hljs-attr">title</span>=<span class="hljs-string">{this.state.title}</span> <span class="hljs-attr">style</span>=<span class="hljs-string">{this.state.style}</span> <span class="hljs-attr">className</span>=<span class="hljs-string">{this.state.className}</span> <span class="hljs-attr">onClick</span>=<span class="hljs-string">{this.linkClicked}</span>&gt;</span>
                {this.props.children}
            <span class="hljs-tag">&lt;/<span class="hljs-name">a</span>&gt;</span>
        )</span>;
    }
}
</code></pre>
]]></content:encoded></item><item><title><![CDATA[What makes your web app faster? (part 4, Progressive Enhancements)]]></title><description><![CDATA[What makes your web app faster? (part 4, Browser And Progressive Enhancements)
If you are coming to this story directly, i’ll suggest to take a look at part 1, part 2 and Part 3 of this series.
So, last time i left you saying,

“Be indistinguishable ...]]></description><link>https://blog.tejpratapsingh.com/what-makes-your-web-app-faster-part-4-progressive-enhancements</link><guid isPermaLink="true">https://blog.tejpratapsingh.com/what-makes-your-web-app-faster-part-4-progressive-enhancements</guid><category><![CDATA[Web Development]]></category><category><![CDATA[web performance]]></category><category><![CDATA[PWA]]></category><category><![CDATA[Browsers]]></category><dc:creator><![CDATA[Tej Pratap Singh]]></dc:creator><pubDate>Tue, 08 Oct 2019 17:52:19 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1570557108166/t3UREqo7m.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h1 id="what-makes-your-web-app-faster-part-4-browser-and-progressive-enhancements-">What makes your web app faster? (part 4, Browser And Progressive Enhancements)</h1>
<p>If you are coming to this story directly, i’ll suggest to take a look at <a target='_blank' rel='noopener noreferrer'  href="/tej-writes/what-makes-your-web-app-faster-part-1-databases-c3899c402d72">part 1</a>, <a target='_blank' rel='noopener noreferrer'  href="/tej-writes/what-makes-your-web-app-faster-part-2-caching-f24cc9a960e5">part 2</a> and <a target='_blank' rel='noopener noreferrer'  href="/tej-writes/what-makes-your-web-app-faster-part-3-client-app-4ec0d4fde428">Part 3</a> of this series.</p>
<p>So, last time i left you saying,</p>
<blockquote>
<p>“Be indistinguishable from native apps.”</p>
</blockquote>
<p>As a web developers we were successful in convincing user to leave there Native Desktop Apps for a web app, Now only few people use an native email client over Gmail. But we are still not able to make user leave there native mobile app for a mobile web app.</p>
<p>This is because a native app feels more comfortable smooth and responsive than a web app. A native app has Push Notification for engagement, Device storage for offline access and much more. But this is changing quickly as web can do more things, check <a target='_blank' rel='noopener noreferrer'  href="https://whatwebcando.today/"><em>what web can do today</em></a>.</p>
<h2 id="-progressive-web-app">* Progressive Web App</h2>
<p>PWA (Progressive Web App) is the next step in making web feel more native to a device.</p>
<p>PWA give you access to native capabilities such as:</p>
<ol>
<li>Offline Storage (Service Worker)</li>
<li>Push Notification (Service Worker)</li>
<li>Install as Native (App Manifest)</li>
<li>Open app links (App Manifest)</li>
</ol>
<blockquote>
<p>To use PWA you must be using https</p>
</blockquote>
<p>PWA has 2 main Service Worker and Web App Manifest</p>
<h2 id="-1-service-worker-https-developer-mozilla-org-en-us-docs-web-api-service_worker_api-"><a target='_blank' rel='noopener noreferrer'  href="https://developer.mozilla.org/en-US/docs/Web/API/Service_Worker_API">1. Service Worker:</a></h2>
<blockquote>
<p>Service workers essentially act as proxy servers that sit between web applications, the browser, and the network (when available). They are intended, among other things, to enable the creation of effective offline experiences, intercept network requests and take appropriate action based on whether the network is available, and update assets residing on the server. They will also allow access to push notifications and background sync APIs.</p>
</blockquote>
<p>To read more about service worker goto <a target='_blank' rel='noopener noreferrer'  href="http://Service workers essentially act as proxy servers that sit between web applications, the browser, and the network (when available"><em>MDN</em></a>. They are intended, among other things, to enable the creation of effective offline experiences, intercept network requests and take appropriate action based on whether the network is available, and update assets residing on the server. They will also allow access to push notifications and background sync APIs.).</p>
<h2 id="-2-web-app-manifest-https-developer-mozilla-org-en-us-docs-web-manifest-"><a target='_blank' rel='noopener noreferrer'  href="https://developer.mozilla.org/en-US/docs/Web/Manifest">2. Web App Manifest:</a></h2>
<blockquote>
<p>The web app manifest provides information about a web application in a JSON text file, necessary for the web app to be downloaded and be presented to the user similarly to a native app (e.g., be installed on the homescreen of a device, providing users with quicker access and a richer experience). PWA manifests include its name, author, icon(s), version, description, and list of all the necessary resources (among other things).</p>
</blockquote>
<p>To read more about web app manifest goto <a target='_blank' rel='noopener noreferrer'  href="https://developer.mozilla.org/en-US/docs/Web/Manifest"><em>MDN</em></a>.</p>
<hr>
<h2 id="other-enhancements-">Other Enhancements:</h2>
<p>As we know javascript executes all operations in a single thread. It becomes a problem while going more intensive tasks such as image processing. To overcome this situation we can transfer that task to <a target='_blank' rel='noopener noreferrer'  href="https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API"><strong><em>Web Worker</em></strong></a> which will execute that task in a background thread. You cannot touch any DOM element from Web Worker and only transfer data using messages. To read more about Web Worker goto <a target='_blank' rel='noopener noreferrer'  href="https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API"><em>MDN</em></a>.</p>
]]></content:encoded></item><item><title><![CDATA[What makes your web app faster? (part 3, Client App)]]></title><description><![CDATA[What makes your web app faster? (part 3, Client App)
If you are coming to this story directly, i’ll suggest to take a look at part 1 and part 2 of this series.
So, last time i left you saying,

“Not everything has to be done on server.”

We are livin...]]></description><link>https://blog.tejpratapsingh.com/what-makes-your-web-app-faster-part-3-client-app</link><guid isPermaLink="true">https://blog.tejpratapsingh.com/what-makes-your-web-app-faster-part-3-client-app</guid><category><![CDATA[Web Development]]></category><category><![CDATA[Browsers]]></category><category><![CDATA[Databases]]></category><category><![CDATA[web performance]]></category><category><![CDATA[server]]></category><dc:creator><![CDATA[Tej Pratap Singh]]></dc:creator><pubDate>Tue, 08 Oct 2019 17:50:16 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1570556875245/C6dNS6eWn.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h1 id="what-makes-your-web-app-faster-part-3-client-app-">What makes your web app faster? (part 3, Client App)</h1>
<p>If you are coming to this story directly, i’ll suggest to take a look at <a target='_blank' rel='noopener noreferrer'  href="/tej-writes/what-makes-your-web-app-faster-part-1-databases-c3899c402d72">part 1</a> and <a target='_blank' rel='noopener noreferrer'  href="/tej-writes/what-makes-your-web-app-faster-part-2-caching-f24cc9a960e5">part 2</a> of this series.</p>
<p>So, last time i left you saying,</p>
<blockquote>
<p><em>“Not everything has to be done on server.”</em></p>
</blockquote>
<p>We are living in a new age of web development, previously everything was done on server side (Rendering, routing etc). After introduction of <a target='_blank' rel='noopener noreferrer'  href="https://en.wikipedia.org/wiki/Ajax_(programming"><strong>AJAX</strong></a>)<strong>,</strong> web development got a whole new way to create and manage user interaction. All the likes, adding comment does not needed a page refresh.</p>
<p>But without using a standard development pattern like MVC, it was getting hard to manage bigger and bigger applications.</p>
<h1 id="javascript-frameworks-">Javascript Frameworks:</h1>
<p>The Dawn Of Web Frameworks begins in 2009 when a guy at google started working on a js framework the made 18,000 lines of jquery code to 2,000 angularjs code (That app was google feedback).</p>
<h2 id="the-reason-why-they-are-so-successful-because-">The reason why they are so successful because:</h2>
<ol>
<li>The use a well proven app development pattern (MVC, MVVC, MV* etc).</li>
<li>Only load parts of web page that is changing (Single page application).</li>
<li>Reusing web components.</li>
<li>If you are using node js server you can user isomorphic javascript for a single codebase.</li>
<li>Takes care of your routing.</li>
</ol>
<h2 id="leaders-">Leaders:</h2>
<p>There are more than 100 frameworks in market, leaders are:</p>
<ol>
<li><a target='_blank' rel='noopener noreferrer'  href="https://angular.io/">Angular</a></li>
<li><a target='_blank' rel='noopener noreferrer'  href="https://facebook.github.io/react/">React</a></li>
<li><a target='_blank' rel='noopener noreferrer'  href="https://vuejs.org/">Vue</a></li>
<li><a target='_blank' rel='noopener noreferrer'  href="https://www.meteor.com/">Meteor</a> (we will be excluding this)</li>
<li><a target='_blank' rel='noopener noreferrer'  href="http://backbonejs.org/">Backbone</a></li>
<li><a target='_blank' rel='noopener noreferrer'  href="http://emberjs.com/">Ember</a></li>
<li><a target='_blank' rel='noopener noreferrer'  href="https://www.polymer-project.org/1.0/">Polymer</a></li>
</ol>
<p>Here is a benchmark of these frameworks fighting for glory,</p>
<p> [## Javascript Frameworks Benchmarks</p>
<h3 id="duration-for-updating-all-1000-rows-of-the-table-with-5-warmup-iterations-">Duration for updating all 1000 rows of the table (with 5 warmup iterations).</h3>
<h4 id="stefankrause-net-http-stefankrause-net-js-frameworks-benchmark4-webdriver-ts-table-html-source-post_page-4ec0d4fde428-">stefankrause.net](http://stefankrause.net/js-frameworks-benchmark4/webdriver-ts/table.html?source=post_page-----4ec0d4fde428----------------------)</h4>
<p>I won&#39;t tell you to use a specific framework over other, you can look at the benchmarks and decide it for yourself.</p>
<p>So, now back to how you can boost your web app’s performance. Using a Javascript framework helps you from generating those heavy HTML pages on server but it also increase time for <strong>first meaningful paint</strong>.</p>
<p>The way our web app rendered is:</p>
<ol>
<li>Get Container (simple page).</li>
<li>Load Javascript framework.</li>
<li>Load Controllers.</li>
<li>Get template (not in case of React).</li>
<li>Get api data.</li>
<li>Render template with data.</li>
</ol>
<p>Which is even <strong>slower than older methods</strong>, just get HTML and BAMM first meaningful paint is here.</p>
<p>But it is still good because, everything that changes from here will be blazing fast and what can never be matched with traditional server pages.</p>
<p>But there is a solution for above problem → <strong>Server Side Rendering.</strong></p>
<h2 id="server-side-rendering-">Server Side Rendering:</h2>
<p>In server side rendering, web app’s are rendered as HTML from server and after serving that 1st page client apps kicks in and takes control of application from there. So, it is a mix of old methods with new technology.</p>
<p>Server side rendering also helps in keeping a single code base, you can achieve this with <a target='_blank' rel='noopener noreferrer'  href="http://phantomjs.org/">phantomJs</a> (it has a npm module).</p>
<p>But i will suggest take one which handles server side rendering itself, this will boost your app performance big time.</p>
<h2 id="-webpack-https-webpack-github-io-"><a target='_blank' rel='noopener noreferrer'  href="https://webpack.github.io/">Webpack</a>:</h2>
<p>Loading multiple javascript files surely takes more time than all file combined as one. Webpack helps you achieve that.</p>
<p>Javascript frameworks are big topic in itself, I will not going to explain you every one of them.</p>
<h2 id="choose-one-choose-wisely-">Choose one Choose Wisely:</h2>
<ol>
<li>One way to choose is, Just have a look at every frameworks homepage, go with the one loads faster.</li>
<li>If you are new to Javascript stay away from things you don&#39;t understand (means stay away from angular 2 or reactjs).</li>
<li>Some people also go for creating a minimal framework themself (They say they only needed that much, so why to include 50kb more).</li>
<li>Other way would be to get one which has everything you need.</li>
</ol>
<p>Personally i would suggest to go for reactjs as they get new and shiny things first. (For now i am so much invested in angularjs, that i cannot leave it. But soon i will give vuejs a try).</p>
<p>OK, it time for another shower thought here:</p>
<blockquote>
<p>“Be indistinguishable from native apps.”</p>
</blockquote>
<p>Native apps always have a sweet spot in user’s heart, let&#39;s change that in next chapter → <strong> <a target='_blank' rel='noopener noreferrer'  href="/tej-writes/what-makes-your-web-app-faster-part-4-progressive-enhancements-583dcfec08ac">Browsers</a> .</strong></p>
]]></content:encoded></item><item><title><![CDATA[What makes your web app faster? (part 2, caching)]]></title><description><![CDATA[What makes your web app faster? (part 2, caching)
If you are looking to boost performance of you web application, then do read part 1 of this series.
So in last part i left you after saying;

“Best way to use database is, not using it at all.”

Readi...]]></description><link>https://blog.tejpratapsingh.com/what-makes-your-web-app-faster-part-2-caching</link><guid isPermaLink="true">https://blog.tejpratapsingh.com/what-makes-your-web-app-faster-part-2-caching</guid><category><![CDATA[Web Development]]></category><category><![CDATA[web performance]]></category><category><![CDATA[server]]></category><category><![CDATA[Databases]]></category><category><![CDATA[Browsers]]></category><dc:creator><![CDATA[Tej Pratap Singh]]></dc:creator><pubDate>Tue, 08 Oct 2019 17:42:42 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1570556438871/mjOYfFz1E.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h1 id="what-makes-your-web-app-faster-part-2-caching-">What makes your web app faster? (part 2, caching)</h1>
<p>If you are looking to boost performance of you web application, then do read <a target='_blank' rel='noopener noreferrer'  href="/what-makes-your-web-app-faster-part-1-databases-c3899c402d72">part 1</a> of this series.</p>
<p>So in last part i left you after saying;</p>
<blockquote>
<p><em>“Best way to use database is, not using it at all.”</em></p>
</blockquote>
<p>Reading database is nothing but reading a well organised file (that is why they are persistent, duh). With use of some amazing algorithms, they are queried, read and written.</p>
<p>But reading a file comes with a cost in terms of cpu utilization and delay to serve those requests. This does not seem big problem when you are serving 4–5 requests per second, but as you reach something like 20–30 requests per second your database starts to show some strange behaviour in serving those requests.</p>
<p>Suppose you run a web app like twitter (<a target='_blank' rel='noopener noreferrer'  href="https://blog.twitter.com/2013/new-tweets-per-second-record-and-how">which serves 143,199 tweets per sec</a> and for read let&#39;s multiply that with 0.2 of <a target='_blank' rel='noopener noreferrer'  href="https://about.twitter.com/">313M Monthly active users</a> which comes close to 8964257.4M reads per sec), It is not possible to query database for every new request, so, solution to this problem is <a target='_blank' rel='noopener noreferrer'  href="https://en.wikipedia.org/wiki/In-memory_database"><strong>in-memory databases</strong></a>.</p>
<h1 id="in-memory-database">in-memory database</h1>
<p>Server today do not have any boundaries (not literally), they have huge processing power, petabytes of petabytes of storage and some terabytes of RAM. With this amazing specs we get liberty to do a lot of operations in runtime and store a lot of things in memory.</p>
<p>Reading and writing to memory is faster than anything else, with this idea came concept of in-memory databases.</p>
<p>There are 2 major solutions for in-memory database:</p>
<ol>
<li>Redis</li>
<li>Memcached</li>
</ol>
<p>There are more but these are the famous once, and that&#39;s what i care about.</p>
<p>Memcached is a little part of Redis, redis is much more than a in-memory key pair database, it has powerful data types, transactions with optimistic locking, fast message channels and much more.</p>
<p>Twitter also uses redis, let me tell how:</p>
<ol>
<li>Tweets made are stored in redis with an associated key.</li>
<li>Tweets are then pushed to users unique timeline which is also stored in redis (this could be the reason why you cannot update your tweet).</li>
<li>There are more questions like what happens to timeline when user follows another user or unfollows a user, but this is how they give you amazing response time.</li>
</ol>
<p>So, key points to note here:</p>
<ol>
<li>Anything which has a large read request but less write request can be stored in a in-memory database.</li>
<li>They can be blog, post or something like a tweet but not who liked post, comments of a post (these generally have a direct access with URL like /postid, /videoid).</li>
</ol>
<p>If RAM is not a problem then there is no reason to not use a in-memory database.</p>
<hr>
<h1 id="some-more-things-that-can-be-done-on-server-side-">Some more things that can be done on server side:</h1>
<ol>
<li>Choose a good server side language, because implementation to handle requests are done by those things, they handle your threads and all sorts of other stuff.</li>
<li>Choose a language that can take proper advantage of your server capabilities. That means, it should use 64 bit data bus if provided, use all 8 or 16 cpu cores if provided.</li>
<li>Here as well, you can use distributed system to form a cluster of servers use it as a load balancer.</li>
</ol>
<p>Now, some more golden words by me:</p>
<blockquote>
<p>“Not everything has to be done on server.”</p>
</blockquote>
<p>Our server is stronger than ever so does our users devices, we will see how to use its power for some more performance boost with our client app in next chapter → <a target='_blank' rel='noopener noreferrer'  href="/@tejpratap/what-makes-your-web-app-faster-part-3-client-app-4ec0d4fde428"><strong>Client App</strong></a>.</p>
]]></content:encoded></item></channel></rss>