<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Abha Gupta on Medium]]></title>
        <description><![CDATA[Stories by Abha Gupta on Medium]]></description>
        <link>https://medium.com/@abhaguptatweet?source=rss-2bc7843b99ec------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*xIeJ0AY9qUt3H2XBs2f7Tw.jpeg</url>
            <title>Stories by Abha Gupta on Medium</title>
            <link>https://medium.com/@abhaguptatweet?source=rss-2bc7843b99ec------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 15:15:30 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@abhaguptatweet/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Run Sitespeed.io on Android devices.]]></title>
            <link>https://medium.com/@abhaguptatweet/run-sitespeed-io-on-android-devices-4777b405faaf?source=rss-2bc7843b99ec------2</link>
            <guid isPermaLink="false">https://medium.com/p/4777b405faaf</guid>
            <category><![CDATA[web-app-performance]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[performance-monitoring]]></category>
            <category><![CDATA[android-performance]]></category>
            <category><![CDATA[appium]]></category>
            <dc:creator><![CDATA[Abha Gupta]]></dc:creator>
            <pubDate>Mon, 20 Nov 2017 09:07:47 GMT</pubDate>
            <atom:updated>2017-11-22T17:14:24.465Z</atom:updated>
            <content:encoded><![CDATA[<p><a href="https://www.sitespeed.io/">Sitespeed.io</a> is an excellent tool to run performance tests for your web applications. Not only does sitespeed.io runs its own performance tools like <a href="https://github.com/sitespeedio/browsertime">browsertime</a>, <a href="https://github.com/sitespeedio/coach">coach</a>, and <a href="https://github.com/sitespeedio/pagexray">pagexray</a>, it gracefully hooks up with popular tools like WebPageTest and other open source tools for performance measurements.</p><p>One of our biggest challenge lately was to run performance tests on real devices. Sitespeed.io provides this <a href="https://www.sitespeed.io/documentation/sitespeed.io/mobile-phones/">capability</a> by connecting via adb but we needed something scalable with least device maintenance cost. Hence we explored the usage of Appium which can connect to multiple devices at a time and will eventually lead us to use device cloud services like Saucelabs and Browserstack.</p><h3>Running tests on real devices locally (Android)</h3><p>Sitespeed.io uses selenium to open up the browser. Which means we can pass a set of desired capabilities to the selenium web driver to run tests on a valid selenium server endpoint. In order to run tests on the devices, we also need to use <a href="http://appium.io/">Appium</a>, which acts as a bridge between selenium driver and device interface adb (in this situation).</p><p>Here are the steps to use Sitespeed.io with Appium:</p><ul><li>Install <a href="https://github.com/appium/appium-desktop/releases/tag/v1.2.6">Appium</a>. There is a <a href="https://www.npmjs.com/package/appium">node module</a> available as well.</li><li>Set up PATH for adb, ANDROID_HOME, JAVA_HOMEetc for Appium. ( appium-doctoris a handy node-module to check what is missing to run Appium successfully).</li><li>If you have an android device connected to your machine, adb devices should list your device.</li><li>Run appium to start your appium server. By default, Appium server runs on port 4723.</li><li>Run following script to run sitespeed.io using appium server.</li></ul><pre><strong>var </strong>sitespeedio = require(&#39;sitespeed.io&#39;);<br><strong>var </strong>options =<br>    {<br>        outputFolder: &#39;sitespeed-result&#39;,<br>        browsertime:{<br>            selenium: {<br>                url: &#39;http://localhost:4723/wd/hub&#39;,<br>                capabilities:{<br>                    &#39;deviceName&#39;:&#39;2e9078d5&#39;,<br>                    &#39;browserName&#39;: &#39;chrome&#39;,<br>                    &#39;appiumVersion&#39;: &#39;1.6.4&#39;,<br>                    &#39;device-orientation&#39;: &#39;portrait&#39;,<br>                    &#39;platformVersion&#39;: &#39;4.4&#39;,<br>                    &#39;platformName&#39;: &#39;android&#39;,<br>                    &#39;enablePerformanceLogging&#39;: &#39;true&#39;<br>                }<br>            },<br>            &#39;iterations&#39;: 3<br>     },<br>      &#39;urls&#39;: [&quot;https://www.example.com/&quot;]<br>    }<br>sitespeedio.run(options);</pre><p><strong>Note</strong> : The Chrome browser version needs to be above 54 for running performance API. Also, note that enablePerformanceLogging:true is an important capability to run this test.</p><p><strong>Update:</strong></p><p>If you are using current released selenium-webdriver:3.6.0, there is a small change that you will have to do in order to make this work. This versiondoes not support methods setPosition and setSize on Window object of Webdriver when run on Chrome on Android. Hence we will need to inject a customized selenium-webdriver to sitespeed.io. Here is how you can do it:</p><pre><strong>var </strong>Window = require(&#39;sitespeed.io/node_modules/selenium-webdriver/lib/webdriver&#39;).Window;<br><strong>var </strong>Options = require(&#39;sitespeed.io/node_modules/selenium-webdriver/lib/webdriver&#39;).Options;<br><strong>var </strong>WebDriver = require(&#39;sitespeed.io/node_modules/selenium-webdriver/lib/webdriver&#39;).WebDriver;<br><br><strong>var </strong>isAndroid = <strong>true</strong>;<br><br><strong>class </strong>AndroidWindow <strong>extends </strong>Window {<br>    constructor(driver){<br>        <strong>super</strong>(driver);<br>    }<br><br>    async setSize(width, height){<br>       <strong>if</strong>(!isAndroid) {<br>         <strong>return super</strong>.setSize(width, height);<br>       }<br>    }<br><br>    async setPosition(x, y) {<br>       <strong>if</strong>(!isAndroid) {<br>            <strong>return super</strong>.setPosition(x, y);<br>        }<br>    }<br>}<br><br><strong>class </strong>AndroidWebDriver <strong>extends </strong>WebDriver {<br>    constructor(session, executor, opt_flow, opt_onQuit) {<br>        <strong>super</strong>(session, executor, opt_flow, opt_onQuit);<br>    }<br>    manage() {<br>        <strong>return new </strong>AndroidOptions(<strong>this</strong>);<br>    }<br>}<br><br><strong>class </strong>AndroidOptions <strong>extends </strong>Options {<br>    constructor(driver){<br>        <strong>super</strong>(driver);<br>    }<br>    window() {<br>        <strong>return new </strong>AndroidWindow(<strong>this</strong>.driver_);<br>    }<br>}<br><br>module.exports =  AndroidWebDriver</pre><p>and then inject this AndroidWebDriver in sitespeed.io script as follows:</p><pre><strong>const </strong>AndroidWebDriver = require(&#39;./custom_selenium_web_driver&#39;);<br><br>require(&#39;sitespeed.io/node_modules/selenium-webdriver/lib/webdriver&#39;).WebDriver = AndroidWebDriver;<br><br><strong>var </strong>sitespeedio = require(&#39;sitespeed.io&#39;);</pre><h3><strong>Running tests on Saucelabs (Android):</strong></h3><p>Saucelabs provides the real devices in the <a href="https://app.testobject.com/#/signup">TestObject</a> account. You can sign up for a trial account and get an API key.</p><pre><strong>const </strong>AndroidWebDriver = require(&#39;./custom_selenium_web_driver&#39;);<br><br>require(&#39;sitespeed.io/node_modules/selenium-webdriver/lib/webdriver&#39;).WebDriver = AndroidWebDriver;<br><br><strong>var </strong>sitespeedio = require(&#39;sitespeed.io&#39;);<strong><br>var </strong>sitespeedio = require(&#39;sitespeed.io&#39;);<br><strong>var </strong>options =<br>    {<br>        outputFolder: &#39;sitespeed-result&#39;,<br>        browsertime:{<br>            selenium: {<br>                url: &#39;https://us1.appium.testobject.com/wd/hub&#39;,<br>                capabilities:{<br>                    &#39;testobject_appium_version&#39;: &#39;1.6.4&#39;,<br>                    &#39;testobject_api_key&#39; : &#39;&lt;API_KEY&gt;&#39;,<br>                    &#39;testobject_device&#39;:&#39;&lt;Device Name&gt;&#39;,<br>                    &#39;browserName&#39;: &#39;browser&#39;,<br>                    &#39;enablePerformanceLogging&#39;: &#39;true&#39;,<br>                    &#39;platformName&#39;: &#39;Android&#39;<br>                }<br>            },<br>            &#39;iterations&#39;: 1</pre><pre>        },<br>        plugins: {<br>           load: &#39;./plugin.js&#39;<br>        },<br>        <br>        &#39;urls&#39;: [&quot;https://www.example.com&quot;]<br>    }</pre><pre>sitespeedio.run(options);</pre><p><strong>Concerns about performance tests on Saucelabs</strong></p><p>You may be wondering if it is reasonable to run performance tests on Saucelabs. It is a valid concern and we pondered on these questions for a while :</p><ul><li>How will we address the network connectivity delay between our network and Saucelabs?</li><li>Will network delay introduce noise to our tests which we cannot control?</li><li>Will the devices be always available for testing?</li><li>Will the tests results be flaky on Saucelabs?</li></ul><p>To answer these questions, we did some 100 tests on devices on Saucelabs and Browserstack and found that there is a ‘<em>somewhat</em>’ constant time in connectivity which we can ignore. Chrome provides performance metrics to sitespeed.io only after it is instantiated on the device. Also, the metrics delivered by sitespeed.io were consistent enough to make them reliable for our testing.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4777b405faaf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Increase your code coverage using Istanbul]]></title>
            <link>https://medium.com/walmartglobaltech/do-you-have-100-code-coverage-10c09a44832b?source=rss-2bc7843b99ec------2</link>
            <guid isPermaLink="false">https://medium.com/p/10c09a44832b</guid>
            <category><![CDATA[istanbul]]></category>
            <category><![CDATA[code-coverage]]></category>
            <category><![CDATA[unit-testing]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[nodejs]]></category>
            <dc:creator><![CDATA[Abha Gupta]]></dc:creator>
            <pubDate>Sun, 12 Mar 2017 05:43:28 GMT</pubDate>
            <atom:updated>2018-04-26T21:21:17.285Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/450/1*jHOlC9JcbLJBREioa7kLog.png" /><figcaption><a href="https://pixabay.com/en/code-code-editor-coding-computer-1839406/">https://pixabay.com/en/code-code-editor-coding-computer-1839406/</a></figcaption></figure><p>Often times, we talk about having 100% code coverage of our projects. Truth is, having 100% code coverage is a shining star on our codebase, but it is extremely hard to accomplish for an existing codebase for which coverage was not the topmost priority in past. The reason is very simple: when you do not write code in a ‘testable’ way, you cannot write unit tests for your code, which means, you cannot have 100% coverage.</p><p>The best way to get 100% coverage is to keep evaluating coverage as you develop the code. In a Test Driven Development (TDD), coverage comes along with the effort. However, in a non-TDD, you need to be very alert on calculating coverage as you go.</p><p>Before we go on, please note that I am not an enforcer of 100% coverage, but driving towards that goal usually enlightens us with lot of hidden flows in the code which we might skip testing otherwise.</p><h4><strong>Tools</strong>:</h4><p>Since I have been working with NodeJS lately, I am going to talk about one of the most popular code coverage tool, <a href="https://www.npmjs.com/package/istanbul">istanbul</a>. Assuming you can get the basics of Istanbul from its own <a href="https://github.com/gotwarlost/istanbul">documentation</a>, I will just present some techniques to use Istanbul to increase the coverage of an existing project.</p><p>Istanbul presents some decent html reports which can be utilized to find code which is not covered.</p><h4><strong>Things to remember</strong>:</h4><ol><li><strong>A piece of code must be testable</strong>. If an exportable module contains a function, it should be created in a way that data can be injected from outside, so that a test can send the data and assert on the desired output. For example,</li></ol><pre>//example module index.js<br>module.exports = {<br>  add: <strong>function</strong>(x, y){<br>      <strong>return </strong>x + y;<br>  }<br>}</pre><pre>//example test<br>describe(<strong>&#39;Index&#39;</strong>, <strong>function</strong>(){<br>    <em>it</em>(<strong>&#39;should add 2 and 3 to give 5&#39;</strong>, <strong>function</strong>(){<br>        expect(<strong>index</strong>.add(2, 3)).<strong>to</strong>.be.equal(5);<br>    });<br>});</pre><pre>//code coverage<br>Statements   : 100% ( 4/4 )<br>Branches     : 100% ( 0/0 )<br>Functions    : 100% ( 1/1 )<br>Lines        : 100% ( 4/4 )</pre><p>2. <strong>Conditional Statements</strong>: These are important for branch coverage. In the following example, the coverage is dropped because test case is not covering the conditional statements.</p><pre>add2: <strong>function</strong>(x, y){<br>    <strong>if </strong>(x &amp;&amp; y){<br>        <strong>return </strong>x + y;<br>    } <strong>else </strong>{<br>        <strong>return null</strong>;<br>    }<br>}</pre><pre>//test<br><strong><em>it</em></strong>(<strong>&#39;should add 2 and 3 to give 5&#39;</strong>, <strong>function</strong>(){<br>    expect(<strong>index</strong>.add2(2, 3)).to.be.equal(5);<br>});</pre><pre>//code coverage<br>Statements   : 85.71% ( 6/7 )<br>Branches     : 75% ( 3/4 )<br>Functions    : 100% ( 2/2 )<br>Lines        : 85.71% ( 6/7 )</pre><p>Fix it by adding a test case for else condition:</p><pre><strong><em>it</em></strong>(<strong>&#39;should return a value based on conditions&#39;</strong>, <strong>function</strong>(){<br>    expect(<strong>index</strong>.add2(2, 3)).to.be.equal(5);<br>});<br><strong><em>it</em></strong>(<strong>&#39;should return null when no value is passed&#39;</strong>, <strong>function</strong>(){<br>    expect(<strong>index</strong>.add2()).to.be.null;<br>});</pre><pre>//code coverage<br>Statements   : 100% ( 10/10 )<br>Branches     : 100% ( 4/4 )<br>Functions    : 100% ( 3/3 )<br>Lines        : 100% ( 10/10 )</pre><p>Another example with an object in picture. Usually we use “short-circuit” evaluation to set default value, but it needs to be tested as well to complete coverage.</p><pre>doSomething: <strong>function </strong>(y) {<br>    <strong>var </strong>x = y || {};  // assign x as y or an empty object<br>    <strong>return </strong>x.val;     <br><br>}<br>//example test</pre><pre><em>it</em>(<strong>&#39;should return expected value &#39;</strong>, <strong>function</strong>(){<br>    expect(<strong>index</strong>.doSomething({<strong>val</strong>: 2 })).to.be.equal(2);<br>});<br><strong><em>it</em></strong>(<strong>&#39;should return expected value &#39;</strong>, <strong>function</strong>(){<br>    expect(<strong>index</strong>.doSomething()).to.be.undefined;<br>});<br>//code coverage<br>Statements   : 100% ( 12/12 )<br>Branches     : 100% ( 6/6 )<br>Functions    : 100% ( 4/4 )<br>Lines        : 100% ( 12/12 )</pre><p>Now a bit of complex functionality.</p><p><strong>3. Async operations and conditions:</strong> Consider a simple example of reading a file:</p><pre>readStatus: <strong>function</strong>(fileName, callback){<br>  fs.readFile(path.join(__dirname , fileName),<strong>&#39;utf-8&#39;</strong>,(<strong>err</strong>, <strong>data</strong>) =&gt;   {<br>        <strong>if</strong>(err) callback(err);<br>        <strong>if </strong>(<strong>data</strong>.length &gt; 0 ) {<br>         <strong>return </strong>callback(<strong>null</strong>, <strong>data</strong>)<br>        }<br>  });<br>}</pre><pre>//test<br>it(<strong>&#39;should read the data from the test file  &#39;</strong>, <strong>function</strong>(done){<br>    <strong>index</strong>.readStatus(<strong>&#39;test.json&#39;</strong>, (err, data) =&gt; {<br>        expect(data).to.<em>equal</em>(<strong>&#39;this is a test file&#39;</strong>)<br>        done();<br>    });<br>});</pre><pre>//coverage<br>Statements   : 94.44% ( 17/18 )<br>Branches     : 80% ( 8/10 )<br>Functions    : 100% ( 5/5 )<br>Lines        : 100% ( 17/17 )</pre><p>Notice that coverage of Statements and Branches has decreased significantly, even though we have a test. Evaluating the report created by Istanbul, you will see something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cSxJj__nu6bkvHDz3lp9Yg.png" /></figure><p>Clearly, the error scenario is not covered. The ‘<strong>I</strong>’ and ‘<strong>E</strong>’ letter signify that if-else condition was not covered for the statements, hence the branch coverage is reduced. In order to fix this, lets create a test which covers the error condition.</p><pre>it(<strong>&#39;should throw an error if the file is not read  &#39;</strong>, <strong>function</strong>(done){<br>    <strong>index</strong>.readStatus(<strong>&#39;notexist&#39;</strong>, (err, data) =&gt; {<br>        expect(err).with.deep.property(<strong>&#39;code&#39;</strong>).to.<em>equal</em>(<strong>&#39;ENOENT&#39;</strong>)<br>        expect(data).to.be.<strong>undefined</strong>;<br>        done();<br>    });<br>});</pre><pre>//coverage<br>Statements   : 100% ( 18/18 )<br>Branches     : 90% ( 9/10 )<br>Functions    : 100% ( 5/5 )<br>Lines        : 100% ( 17/17 )</pre><p>So coverage above is increased for Statements but Branches is still at 90%. That is because, the else part of if(data.length &gt; 0) is not yet tested for. Lets create a test for that. However, there is a flaw in our function under test. It is not returning anything in the callback if file is found but data is empty, ie. data.length is ≤0. So we need to fix the function first :</p><pre>readStatus: <strong>function</strong>(fileName, callback){<br>    fs.readFile(path.join(__dirname , fileName), <strong>&#39;utf-8&#39;</strong>, (<strong>err</strong>, <strong>data</strong>) =&gt; {<br>        <strong>if</strong>(err) callback(err);<br>    <strong>if </strong>(<strong>data</strong>.length &gt; 0 ) {<br>        <strong>return </strong>callback(<strong>null</strong>, <strong>data</strong>)<br>    } <strong>else </strong>{<br>        <strong>return </strong>callback(<strong>null</strong>, <strong>null</strong>)<br>    }<br>  });<br>}</pre><p>Now the test becomes:</p><pre>it(<strong>&#39;should return undefined when file exists but no data is present &#39;</strong>, <strong>function</strong>(done){<br>    <strong>index</strong>.readStatus(<strong>&#39;test_empty.json&#39;</strong>, (err, data) =&gt; {<br>        expect(err).to.be.<strong>null</strong>;<br>        expect(data).to.be.<strong>null</strong>;<br>        done();<br>    });<br>});</pre><pre>//coverage<br>Statements   : 100% ( 19/19 )<br>Branches     : 100% ( 10/10 )<br>Functions    : 100% ( 5/5 )<br>Lines        : 100% ( 18/18 )</pre><p>Example of an API test coverage:</p><pre>// a simple app<br><strong>var </strong>express = require(<strong>&#39;express&#39;</strong>);<br><strong>var </strong>app = express();<br><br><strong>var </strong>people = [<br>    {<br>        <strong>name</strong>: <strong>&#39;John Doe&#39;<br>    </strong>},<br>    {<br>        <strong>name</strong>: <strong>&#39;Jane Doe&#39;<br>    </strong>},<br>    {<br>        <strong>name</strong>: <strong>&#39;Jim Doe&#39;<br>    </strong>}<br>]<br><br>app.use(<strong>&#39;/assets&#39;</strong>, express.static(__dirname + <strong>&#39;/public&#39;</strong>));<br>app.get(<strong>&#39;/people&#39;</strong>, <strong>function</strong>(req, res){<br>    res.send(people);<br>});<br><br><strong>var </strong>server = app.listen(3000);<br>module.exports = server;</pre><p>Corresponding test</p><pre><strong>var </strong>expect = require(<strong>&#39;chai&#39;</strong>).expect;<br><strong>var </strong>request = require(<strong>&#39;supertest&#39;</strong>);<br><br>describe(<strong>&#39;app&#39;</strong>, <strong>function</strong>(){<br>    <strong>var </strong>server;<br>    <strong>beforeEach</strong>(<strong>function</strong>(){<br>        server = require(<strong>&#39;../app&#39;</strong>);<br>    });<br>    <strong>afterEach</strong>(<strong>function </strong>() {<br>        server.close();<br>    });<br>    it(<strong>&#39;should respond with status code 200&#39;</strong>, <strong>function</strong>(done){<br>        request(server)<br>            .get(<strong>&#39;/people&#39;</strong>)<br>            .expect(200)<br>            .end((<strong>err</strong>, res) =&gt; {<br>               expect(res.body).to.be.an(<strong>&#39;array&#39;</strong>);<br>               done();<br>            });<br><br>        })<br>})</pre><pre>//<br>Statements   : 100% ( 9/9 )<br>Branches     : 100% ( 0/0 )<br>Functions    : 100% ( 1/1 )<br>Lines        : 100% ( 9/9 )</pre><p><strong>4. Async operation with conditions : </strong>Consider following api</p><pre>app.get(<strong>&#39;/api/todos/:uname&#39;</strong>, <strong>function</strong>(req, res, next){<br>    Todos.find({<strong>username</strong>: req.<strong>params</strong>.uname}, <strong>function</strong>(err, results){<br>       <strong>if</strong>(err) {<br>            next(err)<br>        }<strong>else</strong>{<br>           res.send(results);<br>       }<br>    });<br>});</pre><p>Corresponding test:</p><pre>it(<strong>&#39;should respond successfully to /api/todos for a username&#39;</strong>, <strong>function</strong>(done){<br>    request(server)<br>        .get(<strong>&#39;/api/todos/test&#39;</strong>)<br>        .expect(200)<br>        .end(<strong>function</strong>(req, res) {<br>            expect(res.<strong>body</strong>).to.be.an(<strong>&#39;array&#39;</strong>);<br>            done();<br>        });<br>});<br>//coverage<br>Statements   : 97.06% ( 33/34 )<br>Branches     : 75% ( 3/4 )<br>Functions    : 100% ( 5/5 )<br>Lines        : 97.06% ( 33/34 )</pre><p>Coverage is down because we have not yet checked for error condition.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pSgaje1Sl3CgH3PBswOzcA.png" /></figure><h3><strong>Introducing Stubs</strong></h3><p>Stubs or mocks play very important part in unit testing. When you do not know how you can encounter an error condition in a normal scenario, you need to use a stub, basically, a mimic of original function, but which is under your control. You can force this function to throw an error the way you want.</p><p>Going back to the above scenario, we need to cover the error condition which is highlighted in pink. sinon is a popular library in Node which can be used for this purpose.</p><p>We create an object of Error and pass it on to stub as a result of the callback from find method on Todos. Notice that we are using the yields API on sinon.stub for this. yields takes the argument list that the callback should be called with.</p><pre><br>it(<strong>&#39;should throw an error when any kind of error is encountered&#39;</strong>, <strong>function</strong>(done){<br>    <strong>var </strong>stub = sinon.stub(Todos, <strong>&#39;find&#39;</strong>);<br>    <strong>var </strong>expectedError = <strong>new </strong>Error(<strong>&#39;oops&#39;</strong>);<br>    stub.yields(expectedError);<br><br>    request(server)<br>      .get(<strong>&#39;/api/todos/test&#39;</strong>)<br>      .expect(<strong>function</strong>(res){<br>        expect(res.error).to.have.deep.property(<strong>&#39;text&#39;</strong>).to.contain(<strong>&#39;oops&#39;</strong>)<br>        })<br>      .end(done);<br>});</pre><p>So our complete test suite looks like below:</p><pre><strong>var </strong>expect = require(<strong>&#39;chai&#39;</strong>).expect;<br><strong>var </strong>request = require(<strong>&#39;supertest&#39;</strong>);<br><strong>var </strong>sinon = require(<strong>&#39;sinon&#39;</strong>);<br><strong>var </strong>Todos = require(<strong>&#39;../models/todomodel&#39;</strong>);<br><strong>var </strong>AssertionError = require(<strong>&quot;assert&quot;</strong>).<strong>AssertionError</strong>;<br><br>describe(<strong>&#39;main app&#39;</strong>, <strong>function</strong>(){<br>    <strong>var </strong>server;<br>    <strong>beforeEach</strong>(<strong>function</strong>(){<br>        server = require(<strong>&#39;../app&#39;</strong>);<br>    });<br>    <strong>afterEach</strong>(<strong>function </strong>() {<br>        server.close();<br>    });<br>    it(<strong>&#39;should respond successfully to /api/todos for a username&#39;</strong>, <strong>function</strong>(done){<br>        request(server)<br>            .get(<strong>&#39;/api/todos/test&#39;</strong>)<br>            .expect(200)<br>            .end(<strong>function</strong>(req, res) {<br>                expect(res.<strong>body</strong>).to.be.an(<strong>&#39;array&#39;</strong>);<br>                done();<br>            });<br>    });<br><br>    it(<strong>&#39;should throw an error when any kind of error is encountered&#39;</strong>, <strong>function</strong>(done){<br>        <strong>var </strong>stub = sinon.stub(Todos, <strong>&#39;find&#39;</strong>);<br>        <strong>var </strong>expectedError = <strong>new </strong>Error(<strong>&#39;oops&#39;</strong>);<br>        stub.yields(expectedError);<br><br>        request(server)<br>            .get(<strong>&#39;/api/todos/test&#39;</strong>)<br>            .expect(500)<br>            .expect(<strong>function</strong>(res){<br>             expect(res.error).to.have.deep.property(<strong>&#39;text&#39;</strong>).to.contain(<strong>&#39;oops&#39;</strong>)<br>            })<br>            .end(done);<br>    });<br><br>});</pre><pre>/coverage<br>Statements   : 100% ( 34/34 )<br>Branches     : 100% ( 4/4 )<br>Functions    : 100% ( 5/5 )<br>Lines        : 100% ( 34/34 )</pre><h3>Summary:</h3><p>A code base with 100% coverage gives your code a shield of protection against some of the unforeseen errors. Even though some errors do not make sense, the effort of covering your code 100% makes you go through certain scenarios, which you may not otherwise. And that results in a solid software product which you can be confident about.</p><p><strong>Useful resources:</strong></p><ul><li><a href="http://jstest.jcoglan.com/mocking.html">jstest</a></li><li><a href="https://martinfowler.com/bliki/TestCoverage.html">bliki: Test Coverage</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=10c09a44832b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/walmartglobaltech/do-you-have-100-code-coverage-10c09a44832b">Increase your code coverage using Istanbul</a> was originally published in <a href="https://medium.com/walmartglobaltech">Walmart Global Tech Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Webstorm tricks for node development]]></title>
            <link>https://medium.com/@abhaguptatweet/webstorm-tricks-for-node-development-d13dede4c17b?source=rss-2bc7843b99ec------2</link>
            <guid isPermaLink="false">https://medium.com/p/d13dede4c17b</guid>
            <category><![CDATA[webstorm]]></category>
            <category><![CDATA[coding-style]]></category>
            <category><![CDATA[eslint]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[node]]></category>
            <dc:creator><![CDATA[Abha Gupta]]></dc:creator>
            <pubDate>Thu, 23 Feb 2017 21:35:19 GMT</pubDate>
            <atom:updated>2017-05-01T19:57:47.029Z</atom:updated>
            <content:encoded><![CDATA[<p>Jetbrains has provided some excellent <a href="https://www.jetbrains.com/help/webstorm/2016.3/quick-start-guide.html">docs</a> on how to use Webstorm effectively. However, for basic simple things, I have found myself struggling with getting some pin-pointed tips for fast coding. So here is my contribution. Hope it helps.</p><h4>Code Editing:</h4><ol><li><strong>Find everywhere</strong> : Shift+Shift</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/424/1*wA2w5oL3PAmiVBSPVOWbrA.gif" /><figcaption>Search everywhere</figcaption></figure><p><strong>2. Multi-cursor selection</strong> for combined editing: bring the cursor to the text, press Alt+click</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/424/1*9Q654g2fzLhhOc23dQHjEg.gif" /><figcaption>Multi-cursor selection</figcaption></figure><p>3. <strong>Refactor variable in whole file</strong> : select variable , control +T</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/629/1*KVp2xwqr78GX0aeXLu2YIQ.gif" /><figcaption>Refactor a variable</figcaption></figure><p>OR use <strong>Search</strong> and click <strong>Select all occurrences</strong> by clicking Control + Command + G or clicking the button on right most of the search input field.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/1*BFZDx717G7nX6ey43ttMqg.gif" /><figcaption>refactor a variable using search all occurences</figcaption></figure><p>4. <strong>Refactor a variable only for a scope: </strong>Fn + F6</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/965/1*nJbD3X6vbulAvUD0BQgztw.gif" /></figure><p>5. <strong>Extended selection</strong> using keyboard: place the cursor at start of line and press Alt + Up Arrow . Shrink selection : Alt + Down arrow.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/629/1*l6VaLqOsR99BHHMPPPf-6g.gif" /><figcaption>Extend selection</figcaption></figure><p>6. A whole list of shortcuts are described in Webstorm &gt; Preference &gt; Keymap</p><h3>External Tools</h3><ol><li><strong>Auto ESLint Fix</strong>: (applicable only if you use eslint for your project)</li></ol><ul><li>Preferences &gt; Tools &gt; External Tools</li><li>Click +` to add a new external tool</li><li>Enter the values as shown below. Please note that the entry in Program field should be eslint if the program is installed globally. If installed locally, please change it to ./node_modules/.bin/eslint</li><li>Click Apply &gt; OK</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1003/1*RmrmHC2kBmDLkc2VToGHVA.png" /></figure><ul><li>When ready to lint : Right Click at project &gt; External Tools &gt; ESLint Autofixer</li></ul><p><strong>2</strong>. Enable the <strong>JSLint </strong>and <strong>JSHint</strong> Plugins of webstorm for quick fixes and suggestions on code.</p><ul><li>Enable it from WebStorm &gt;Preferences &gt;Languages and Frameworks &gt;JavaScript &gt;Code Quality Tools &gt;JSLint/JSHint.</li></ul><h3><strong>Debugging Tools:</strong></h3><ol><li><strong>Run</strong> : Right click on a file and click <strong>Run &lt;file&gt;</strong>. This creates automatic Run profile.</li><li><strong>Debug</strong> : Right click on a file and click <strong>Debug &lt;file&gt;</strong>. This creates automatic Debug profile. By default, this creates a Node Debug profile. But if the file is a test spec, you might have to <strong>Edit the Configuration</strong> to select Mocha or which ever test suite you are using.</li><li><strong>Debug only one test from test suite: </strong>From the debug panel in the Debug window, click only the test which you want to run.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/697/1*1dygJ87izM3OLM6wxCpdPQ.gif" /><figcaption>Call only one test case</figcaption></figure><p>You can also do the above by adding it.only to run just one test.</p><ol><li><strong>Add/Edit Debug profiles: </strong>Edit Configurations from Run menu, click ‘Edit Configurations’</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/440/1*IruizaC2Ku5I1Xh5dXVwhg.png" /></figure><p>Click + .</p><p>If running a node process, select Node and fill the elements that is needed for running the process.</p><p>If running mocha test, select Mocha and fill the elements required.</p><h3>Webstorm NPM Tools Window:</h3><p>If Node is already installed on the system, you will have npm tools window already enabled. This shows up in the left bottom corner of the window</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/165/1*NlMk_Nn3SuqvqLcEST9xCQ.png" /></figure><p>Click npm to open up npm tools window and run the command directly from here.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/372/1*WLXp3_ZdsmcONaKHW_EpQw.png" /></figure><h3><strong>Webstorm Version Control with Github.</strong></h3><p>If your code is already connected to Github, you can use the Version Control tool window automatically. View &gt; Tools Window &gt; Version Control. You can have shortcut in created in Tools Panels.</p><p>To see the difference in code from local to repository. Click the File you want to see the difference for and click on the icon on left for difference. Or right click on file and select ‘Show Diff’</p><h3>References :</h3><p><a href="https://blog.jetbrains.com/webstorm/2015/06/10-webstorm-shortcuts-you-need-to-know/">https://blog.jetbrains.com/webstorm/2015/06/10-webstorm-shortcuts-you-need-to-know/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d13dede4c17b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Testing the right way]]></title>
            <link>https://medium.com/walmartglobaltech/testing-the-right-way-d121334834a?source=rss-2bc7843b99ec------2</link>
            <guid isPermaLink="false">https://medium.com/p/d121334834a</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[unit-testing]]></category>
            <category><![CDATA[software-testing]]></category>
            <category><![CDATA[mock]]></category>
            <category><![CDATA[testing]]></category>
            <dc:creator><![CDATA[Abha Gupta]]></dc:creator>
            <pubDate>Sat, 17 Dec 2016 19:31:41 GMT</pubDate>
            <atom:updated>2017-01-25T21:14:43.730Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*vpjSiIqMBBEBaltJ4Aer1w.jpeg" /><figcaption>Photo Credit : <a href="https://pixabay.com/en/board-school-uni-learn-work-test-361516/">Test right way</a></figcaption></figure><p>A lot of times we find people testing their application incorrectly. This includes myself until few months ago. In order to have robust testing, it is very important that we understand what are we testing. I will demonstrate this with a few scenarios below:</p><p>1. <strong>Front end Development</strong> : A front end developer should focus their testing only on the front end. For example, if there is a button on a page which updates a piece of information, then the test scope should be confined by the front end change and should be isolated from any backend dependencies such as whether the information was actually saved by backend. This test case should look like :</p><ul><li>Open web page</li><li>enter information X</li><li>click “Update” button</li><li>Assert “Successful” text is shown.</li></ul><p>2.<strong> Backend development </strong>: Similarly, backend code should focus on testing only the backend portion . So, here the test should look something like :</p><ul><li>Open connection to backend.</li><li>execute API with information X</li><li>Assert “X” is updated</li></ul><p>This is the only way you can guarantee 100% that both component are actually tested.</p><p>3. <strong>Mixed :</strong> If we intermingle the scopes and come up with something like :</p><ul><li>Open web page</li><li>Update the information X.</li><li>Wait for the application to come back.</li><li>Assert whether ‘X’ was updated.</li></ul><p>The above is doable but becomes a victim of dependency on network, availability of web services and latency or HTTP responses, which are not under our control. The result would be flaky, hard to maintain and unreliable tests. Such tests fall into a category of integration tests and serve their purpose only if you have very robust and fail-safe code with enough time-lag to address network and system delays. There is a place for such tests but they should be fewer as advised by the principles of the <a href="http://martinfowler.com/bliki/TestPyramid.html">test pyramid</a>.</p><h3>Mocks</h3><p>Mocks play a very important role in testing. How are mocks used? Let us go through the scenarios. In the first scenario for front end test, mocks will only contain the response which backend API is supposed to return. So instead of actually calling the backend API, you would just assume the response and save it in a file called mock or fixture and perform your front end testing using that.</p><p>In the second scenario it will be other way round. Mocks will contain the mock information that front end is supposed to send. Basically, you are testing API to provide an assertion “I don’t care about where you call me from, when you call me (correctly), I will update this piece of information” .</p><h4>Mock Servers</h4><p>A lot of mock servers are available which provide a mocking infrastructure and a plug-and-play tuning with your tests. But a lot of times, we use these mock servers incorrectly, and expect them to behave in a certain way, so that our tests are green. But trust me, a mock server is just a convenience for you to not create fixtures manually. Mock servers do not and should not have the logic to convert mocked responses based on a test logic. If that happens, then mock server is not a mock server. It is something else.</p><h3>Summary</h3><p>Proper testing involves its own design principles and has to be thought through in detail. It involves making a mental model of your app and thinking what you want to be sure of regarding your application. If you understand the scope of your app and boundaries of control you have, then testing becomes easy. Fortunately, we have a lot of frameworks which do ground work for us. Most modern languages such as Java, Node, iOS, Ruby on Rails, or Python come with great testing frameworks. If we use these tools well and follow the guidelines mentioned here, we can create easy to use, maintainable and robust test cases.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d121334834a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/walmartglobaltech/testing-the-right-way-d121334834a">Testing the right way</a> was originally published in <a href="https://medium.com/walmartglobaltech">Walmart Global Tech Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Android Testing with Mocking]]></title>
            <link>https://medium.com/walmartglobaltech/android-testing-with-mocking-fcec5b9f71c2?source=rss-2bc7843b99ec------2</link>
            <guid isPermaLink="false">https://medium.com/p/fcec5b9f71c2</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[https]]></category>
            <category><![CDATA[wiremock]]></category>
            <category><![CDATA[mocking]]></category>
            <dc:creator><![CDATA[Abha Gupta]]></dc:creator>
            <pubDate>Thu, 30 Jun 2016 18:39:26 GMT</pubDate>
            <atom:updated>2016-11-18T20:50:31.077Z</atom:updated>
            <content:encoded><![CDATA[<p>Android test automation in device farms is becoming a norm these days. Massive scaling of tests on different devices with optimal speed and utmost reliability has driven the testing community to come up with different mocking solutions. A large number of these solutions provide a hosted version of a mock server which runs as an instance and can be accessed to stub service endpoints using a mock server.</p><p>Often, automated web tests are executed in a continuous integration system like Jenkins, in which a master job creates multiple child jobs which each:</p><ul><li>open a connection to a cloud service provider</li><li>build the code</li><li>start the mock server and app</li><li>interact with mocked endpoints to drive the tests</li></ul><p>However, with android native apps, the challenge is little harder because there is no application server or a mock server to start. The APK file is what you have which is uploaded to the device in cloud to run the test. This creates a need of running mock server as a part of the APK itself.</p><p>There are number of mock servers which can do the job. We investigated a few of them and finally selected wiremock for reasons mentioned below.</p><h3>Wiremock on Android</h3><p>Wiremock runs over a Jetty container which makes it perfect candidate to run in Android application. The wiremock jar can be imported as a jar in an android project and the mock server can be started as following :</p><pre>WireMockServer <strong>wireMockServer </strong>= <strong>new </strong>WireMockServer(8080);</pre><p>Sam Edward’s <a href="http://handstandsam.com/2016/01/30/running-wiremock-on-android/">blog</a> gives us a good starting point to run wiremock on Android.</p><h3>HTTPS endpoints</h3><p>Wiremock supports HTTPS using Java Key Store (JKS) as default keystore type. However, android JVM does not support JKS and the default keystore type in Android is <a href="https://bouncycastle.org/specifications.html">Bouncy Castle Keystore (BKS)</a>. Hence there are couple of steps that needs to be taken to get HTTPS working on Android with wiremock.</p><p>Here are the steps you can follow to get things going :</p><p><em>Note that these instructions are provided to generate a self-signed certificate which is not applicable for production environments.</em></p><h4>Adding the service provider in your JVM</h4><ul><li>Open the file as root <strong>&lt;JavaHome&gt;/jre/lib/security/java.security</strong></li><li>Add line <strong>security.provider.11=org.bouncycastle.jce.provider.BouncyCastleProvider </strong>at the the end of all service.providers.</li><li>Save and exit the file.</li><li>Sometimes the JVM settings need a system restart to take effect.</li></ul><h4>Create a BKS Keystore</h4><ul><li>Download the <a href="http://www.keystore-explorer.org/">Keystore Explorer</a> or <a href="http://portecle.sourceforge.net/">Portecle</a> open source tools. Both the softwares work almost same.</li><li>From the menu, click “Create a New Keystore”</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/667/1*Q5T3korWEDZv8Ck7LFalmQ.png" /></figure><ul><li>Select BKS-V1 as Keystore</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/432/1*HtbnkuYpceodGRt_C8oRdA.png" /></figure><ul><li>You will see a new empty keystore created without a key pair.</li><li>Click Save.</li><li>You will be prompted for a password. Type ‘password’ for simplicity sake, because this is what Wiremock chooses by default. Type the same password for Confirm password field.</li><li>Save the Keystore with a filename. The file name can be any file name but sake of clarity, you can give a extension, e.g keystore_bks.</li><li>Generate a key part and self-signed certificate by following these steps:</li><li>Click on “Generate Key Pair” button on top menu</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/576/1*x0niVI38HjvSX88Hd2YM7g.png" /><figcaption>Generate Key Pair</figcaption></figure><ul><li>A dialog box will appear. Select OK without changing anything.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/438/1*79WLc3p2KQzBZBmrqmKPTA.png" /></figure><ul><li>A new dialog will appear</li><li>Click on the Book Icon as shown below:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/574/1*ptRuron5MpRSic5ka1IXmg.png" /></figure><ul><li>Enter the information for certificate request after prompted :</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/432/1*h56juzbk2Fdv9OTowFJuZA.png" /></figure><ul><li>Click OK after entering the complete information.</li><li>Click OK again after verification</li><li>Enter an Alias when prompted. You can enter ‘android_keystore’.</li><li>Enter the password here. This should match the password you entered. Our password is ‘password’</li><li>Click OK</li><li>At this time your BKS keystore should be ready to use.</li></ul><h3>Wiremock updates:</h3><p>The changes done to wiremock to support BKS Keystore type are :</p><ul><li>In class <strong>wiremock/src/main/java/com/github/tomakehurst/wiremock/jetty9/JettyHttpServer.java</strong>, ‘<strong>createHttpsConnector</strong>’ sets the keystore type by system’s keystore type.</li></ul><pre><strong>private </strong>ServerConnector createHttpsConnector(<br>        HttpsSettings httpsSettings,<br>        JettySettings jettySettings) {</pre><pre><em>//Added to support Android https communication.<br></em><strong>CustomizedSslContextFactory sslContextFactory = new CustomizedSslContextFactory();<br>    sslContextFactory.setKeyStorePath(httpsSettings.keyStorePath());</strong><br>    sslContextFactory.setKeyManagerPassword(httpsSettings.keyStorePassword());<br>    <strong>sslContextFactory.setKeyStoreType(httpsSettings.keyStoreType());</strong><br>    <strong>if </strong>(httpsSettings.hasTrustStore()) {<br>        sslContextFactory.setTrustStorePath(httpsSettings.trustStorePath());<br>        sslContextFactory.setTrustStorePassword(httpsSettings.trustStorePassword());<br>        <strong>sslContextFactory.setTrustStoreType(httpsSettings.trustStoreType());</strong><br>    }<br>    sslContextFactory.setNeedClientAuth(httpsSettings.needClientAuth());<br><br>    HttpConfiguration httpConfig = createHttpConfig(jettySettings);<br>    httpConfig.addCustomizer(<strong>new </strong>SecureRequestCustomizer());<br><br>    <strong>final int </strong>port = httpsSettings.port();<br><br>    <strong>return </strong>createServerConnector(<br>            jettySettings,<br>            port,<br>            <strong>new </strong>SslConnectionFactory(<br>                    sslContextFactory,<br>                    <strong>&quot;http/1.1&quot;<br>            </strong>),<br>            <strong>new </strong>HttpConnectionFactory(httpConfig)<br>    );<br>}</pre><p>Note that code will receive the system’s keystore type automatically.</p><ul><li>A new class <strong>CustomizedSslContextFactory.java</strong> is created which overrides ‘<strong>customize</strong>’ method since Android does not have the method ‘<strong>setEndpointIdentificationAlgorithm</strong>’<em> </em>in SSLParams.java</li></ul><pre><strong>public class </strong>CustomizedSslContextFactory <strong>extends </strong>org.eclipse.jetty.util.ssl.SslContextFactory  {<br><br>    <strong>public void </strong>customize(SSLEngine sslEngine)<br>    {<br>        SSLParameters sslParams = sslEngine.getSSLParameters();<br>        <em>// sslParams.setEndpointIdentificationAlgorithm(_endpointIdentificationAlgorithm);<br>        </em>sslEngine.setSSLParameters(sslParams);<br><br>        <strong>if </strong>(<strong>super</strong>.getWantClientAuth())<br>            sslEngine.setWantClientAuth(<strong>super</strong>.getWantClientAuth());<br>        <strong>if </strong>(<strong>super</strong>.getNeedClientAuth())<br>            sslEngine.setNeedClientAuth(<strong>super</strong>.getNeedClientAuth());<br><br>        sslEngine.setEnabledCipherSuites(<strong>super</strong>.selectCipherSuites(<br>                sslEngine.getEnabledCipherSuites(),<br>                sslEngine.getSupportedCipherSuites()));<br><br>        sslEngine.setEnabledProtocols(<strong>super</strong>.selectProtocols(sslEngine.getEnabledProtocols(),sslEngine.getSupportedProtocols()));<br>    }<br><br><br><br>}</pre><h3>Android App Updates</h3><ul><li>If you are building wiremock locally, wiremock jar is generated by running <strong>./gradlew assemble</strong> . This gets saved in ‘<strong>builds/libs’.</strong></li><li>Copy the wiremock jar in the Android projects under <strong>&lt;root&gt;/builds/libs</strong> directory.</li><li>In Android project’s <strong>build.gradle</strong> file, following dependencies needs to be added:</li></ul><pre><strong>def </strong>versions = [<br>        jackson: <strong>&#39;2.6.1&#39;</strong>,<br>        jetty  : <strong>&#39;9.2.13.v20150730&#39;<br></strong>]</pre><pre>dependencies {<br>compile <strong>&quot;com.google.guava:guava:18.0&quot;<br></strong>compile <strong>&quot;org.eclipse.jetty:jetty-server:</strong>$versions.jetty<strong>&quot;<br></strong>compile <strong>&quot;org.eclipse.jetty:jetty-servlet:</strong>$versions.jetty<strong>&quot;<br></strong>compile <strong>&quot;org.eclipse.jetty:jetty-servlets:</strong>$versions.jetty<strong>&quot;<br><br></strong>compile <strong>&quot;com.fasterxml.jackson.core:jackson-core:</strong>$versions.jackson<strong>&quot;</strong>,<br>        <strong>&quot;com.fasterxml.jackson.core:jackson-annotations:</strong>$versions.jackson<strong>&quot;</strong>,<br>        <strong>&quot;com.fasterxml.jackson.core:jackson-databind:</strong>$versions.jackson<strong>&quot;<br></strong>compile <strong>&quot;org.apache.httpcomponents:httpclient:4.5&quot;<br></strong>compile <strong>&quot;org.skyscreamer:jsonassert:1.2.3&quot;<br></strong>compile <strong>&quot;xmlunit:xmlunit:1.6&quot;<br></strong>compile <strong>&quot;com.jayway.jsonpath:json-path:2.0.0&quot;<br></strong>compile <strong>&quot;org.slf4j:slf4j-api:1.7.12&quot;<br></strong>compile <strong>&quot;net.sf.jopt-simple:jopt-simple:4.9&quot;<br><br></strong>compile fileTree(dir: <strong>&#39;libs&#39;</strong>, include: <strong>&#39;wiremock-2.0.8-beta.jar&#39;</strong>)</pre><pre>androidTestCompile <strong>&#39;org.apache.httpcomponents:httpclient-android:4.3.5.1&#39;<br>}</strong></pre><pre>configurations {<br>    all*.exclude group: <strong>&#39;commons-logging&#39;</strong>, module: <strong>&#39;commons-logging&#39;<br>    </strong>all*.exclude group: <strong>&#39;com.android.support&#39;</strong>, module: <strong>&#39;support-annotations&#39;<br>    </strong>all*.exclude group: <strong>&#39;asm&#39;</strong>, module: <strong>&#39;asm&#39;<br></strong>}</pre><ul><li>If you are directly using the published wiremock library, your build.gradle entry will be as follows :</li></ul><pre>androidTestCompile(<strong>&quot;com.github.tomakehurst:wiremock:2.0.8-beta&quot;</strong>) </pre><ul><li>Push the BKS keystore generated earlier in emulator’s <strong>/sdcard/</strong> location. To do this, start your emulator and run ‘<strong>adb push &lt;keystore file&gt; /sdcard/.</strong>’</li><li>In the test code, start the Wiremock server as follows :</li></ul><pre>WireMockServer <strong>wireMockServer  </strong>= <strong>new </strong>WireMockServer(<em>wireMockConfig</em>().port(BuildConfig.<strong><em>PORT</em></strong>).httpsPort(9943).keystoreType(<strong>&quot;BKS&quot;</strong>).keystorePath(<strong>&quot;/sdcard/keystore_bks&quot;</strong>));</pre><ul><li>Stub responses :</li></ul><pre>String uri = <strong>&quot;/api/840dbdf2737a7ff9/conditions/q/CA/atlanta.json&quot;</strong>;<br><br>String jsonBody = <em>asset</em>(getApplication(), <strong>&quot;atlanta-conditions.json&quot;</strong>);<br><em>assertFalse</em>(jsonBody.isEmpty());<br><strong>wireMockServer</strong>.stubFor(<em>get</em>(<em>urlMatching</em>(uri))<br>        .willReturn(<em>aResponse</em>()<br>                .withStatus(200)<br>                .withBody(jsonBody)));</pre><ul><li>Access the stubbed asset at https protocol</li></ul><pre>String serviceEndpoint = <strong>&quot;https://127.0.0.1:&quot; </strong>+ 9943;</pre><ul><li>Call the url (we are using OkHttpClient)</li></ul><pre>OkHttpClient okHttpClient = HttpsSettings.<em>allowAllCertificates</em>();<br>Request request = <strong>new </strong>Request.Builder()<br>        .url(https://medium.com/serviceEndpoint%20+%20uri)<br>        .build();<br><br>Response response = okHttpClient.newCall(request).execute();</pre><ul><li>For a running example, you can clone <a href="https://github.com/abhagupta/AndroidHttpMockingExamples">https://github.com/abhagupta/AndroidHttpMockingExamples</a> repo, thanks to <strong>Sam Edwards </strong>for providing original code for android mocking . Here is his <a href="https://github.com/handstandsam">repo</a>.</li></ul><p>Example: <a href="https://github.com/abhagupta/AndroidHttpMockingExamples/blob/master/app/src/androidTest/java/com/handstandsam/httpmocking/tests/wiremock/WireMockApplicationTestCase.java">https://github.com/abhagupta/AndroidHttpMockingExamples/blob/master/app/src/androidTest/java/com/handstandsam/httpmocking/tests/wiremock/WireMockApplicationTestCase.java</a> is the test that imports the keystore and runs the test.</p><h3>Summary</h3><p>Mocking on Android is very handy for creating reliable tests. Wiremock provides this feature of running the server inside the app itself make it an excellent candidate to run it for android application.With the latest updates in wiremock, you can create a massive parallel test suite for android apps.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fcec5b9f71c2" width="1" height="1" alt=""><hr><p><a href="https://medium.com/walmartglobaltech/android-testing-with-mocking-fcec5b9f71c2">Android Testing with Mocking</a> was originally published in <a href="https://medium.com/walmartglobaltech">Walmart Global Tech Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>