<?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 Swapnil on Medium]]></title>
        <description><![CDATA[Stories by Swapnil on Medium]]></description>
        <link>https://medium.com/@swapnilPadaya?source=rss-d5547818225b------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*bfFJCcZpys1vZTGSP6fA-Q.jpeg</url>
            <title>Stories by Swapnil on Medium</title>
            <link>https://medium.com/@swapnilPadaya?source=rss-d5547818225b------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 19 Nov 2026 03:46:44 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@swapnilPadaya/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[Get Android Unit Test Reports Using Gradle Commands.]]></title>
            <link>https://medium.com/@swapnilPadaya/get-android-unit-test-reports-using-gradle-commands-358bc9b251f6?source=rss-d5547818225b------2</link>
            <guid isPermaLink="false">https://medium.com/p/358bc9b251f6</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[automation]]></category>
            <category><![CDATA[modularization]]></category>
            <category><![CDATA[gradle]]></category>
            <category><![CDATA[jacoco]]></category>
            <dc:creator><![CDATA[Swapnil]]></dc:creator>
            <pubDate>Fri, 12 May 2023 17:48:18 GMT</pubDate>
            <atom:updated>2023-05-12T18:11:10.941Z</atom:updated>
            <content:encoded><![CDATA[<p>It’s important to write unit test cases for software to deliver a platform that customers can rely on. We have to know the percentage of unit test coverage for our entire Android project so that we can cover the rest and catch bugs before going to production.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RdZB8hkVWdTv9YHQYH79YQ.png" /></figure><p>Finding test coverage for your app involves a lot of manual work, and the task gets mind-numbing when unit test coverage needs to extend to separate modules, each class in a package (e.g., a total coverage report of module A package B + module C package D for classes E, F, and G). The number of unit test coverage combinations would drive anyone batty</p><blockquote>WHAT IF I TELL YOU THAT ALL THIS CAN BE AUTOMATED AND WITH JUST ONE GRALDE COMMAND YOU CAN GET COMPLETE REPORT OF THE TEST COVERAGE YOU WANT</blockquote><p>We’ll be using <a href="https://github.com/jacoco/jacoco">Jacoco Library</a> to generate a unit test coverage report in html, xml, or csv format</p><h3>What is Jacoco Library?</h3><p>Jacoco measures the lines and branch coverage that are performed by the Unit test, generating a visual report with detailed insight into code coverage including the number of covered lines and the total percentage of executed code in each method.</p><h3>Why Jacoco Library?</h3><ul><li>Supports multi-module and multi-flavored projects.</li><li>You can define an inclusion or exclusion list for classes/packages you want UT coverage for.</li><li>Provides a detailed breakdown of the report. <br>E.g. Each function coverage report, i.e. whether the function is fully unit tested or not.</li><li>Option to export the coverage report in XML, CSV, or HTML format.</li></ul><p>All of this is good but am sure you would be interested in how jacoco works internally and how is the library providing UT reports. 🤔</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/620/1*tspK-xSCWeRT_-uDaUgKmg.jpeg" /></figure><h3>How does Jacoco Work?</h3><p>Jacoco uses <em>.class</em> file for finding the test coverage for the particular class. Jacoco will go through each <em>.class</em> file generated when UT’s run, and on post successful completion of all UT’s jacoco will create a single <em>.exec</em> file which is a combination of all <em>.class</em> files and has information on how many times a particular line of a code has hit. The same <em>.exec</em> file is then used in combination with the .java/ .kt files for generating a coverage-report file (i.e XML, CSV or HTML)</p><p><strong>Why would one use Jacoco? </strong><em>To create a coverage report? Yes. Well, Here we can create coverage reports for single-module applications as well as for multi-module applications.</em></p><p><strong>Let’s see how to create a report for single-module using Jacoco 📑</strong></p><p>Let’s have a sample app module with some random packages and classes for Example purpose lets take app module from below.</p><pre>app (Module)<br>|<br>|------ network (Package)<br>|         |---- Handler.kt<br>|         |---- HttpCaller.java<br>|         <br>|------ repository (Package)<br>|         |---- NetworkCache.kt<br>|         |---- Database.java<br>|<br>|------ utils (Package)<br>|         |---- Few Utils Classes<br>|         |---- Few Utils Classes<br>|         |---- NetworkUtils.kt<br>|<br>|------ activities(Package)<br>|         |---- Few Activities<br>|<br>|------ services(Package)<br>|         |---- Few Services</pre><p><strong>Single Module<br></strong>In the above example, we can see there is only a single module, and we need to find Unit test coverage for the app module, Where the test coverage only includes<br>👉 com.example.network/<br>👉 com.example.repository/<br>👉 com.example.utils.NetworkUtils.kt</p><p><strong>Let’s see how we can use Jacoco one by one.</strong></p><p><strong>JacocoReport</strong> is responsible for processing <em>.class</em> files with <em>.java / .kt</em> files for creating <em>.exec</em> file and generating a coverage-report file by executing the <em>.exec</em> file.</p><p><strong>So from where would we get </strong><em>.class</em><strong> files in the first place?</strong></p><ul><li>Well, <em>.class</em> files are generated when we are running the Tests and since we need <em>.class</em> files, Jacoco has a dependency on first running the Unit Tests of the module you want to get the coverage for since running UTs for the module creates <em>.class</em> files for each classes present in that module.</li><li>You can find the <em>.class</em> files inside <em>&lt;moduleName&gt;/build/intermediates/javac/esperDebug/classes</em> for all .java files and <em>&lt;moduleName&gt;/build/tmp/kotlin-classes/esperDebug</em> for all .kt files</li></ul><p><strong>Now we have found </strong><em>.class</em><strong> files. Next is to feed which all </strong><em>.class</em><strong> files should be included or excluded in the Coverage Report to Jacoco</strong>🧑‍🏫</p><ul><li>Let&#39;s create a list of all the files needed for the report</li></ul><pre>appFileFilter = [&quot;**/example/network/&quot;,<br>                 &quot;**/example/repository/&quot;,<br>                 &quot;**/example/utils/NetworkUtils.*&quot;]</pre><ul><li>Creating a list that will have <em>.class</em> files that need to exclude or include respective, For that we’ll use <strong>fileTree</strong></li></ul><pre>appJavaFileTree = fileTree(dir: &quot;${project(&#39;:app:&#39;).getProject().buildDir}/intermediates/javac/Debug/classes&quot;, includes: appFileFilter)<br>appKotlinFileTree = fileTree(dir: &quot;${project(&#39;:app:&#39;).getProject().buildDir}/tmp/kotlin-classes/Debug&quot;, includes: appFileFilter)</pre><ul><li>Now we have our <em>filetree</em> ready and we need to feed it to Jacoco for execution, For this we’ll use <em>classDirectories.from</em> this will take in the files that we excluded or included to create the <em>.exec</em> file.</li></ul><pre>classDirectories.from = files([appJavaFileTree], [appKotlinFileTree])</pre><ul><li>Now we need to execute <em>.exec</em> file which will be used in the execution of data files during coverage analysis</li></ul><pre>executionData.from = file(&quot;${project.buildDir}/jacoco/testUnitTest.exec&quot;)</pre><p><strong>We‘ve feed Jacoco with </strong><em>.class</em><strong> and </strong><em>.exec</em><strong><em> files</em>, Now Next we need to tell jacoco what files are we generating Coverage for?</strong></p><ul><li>This time will use src/main/java which contains all the classes in the app module and pass it as</li></ul><pre>def coverageSourceDirs = [&quot;src/main/java&quot;]<br>sourceDirectories.setFrom(files(coverageSourceDirs))</pre><ul><li>These files are different than the 2 files we passed previously i.e. <em>.class</em> and .<em>exec, This 2 files </em>will work together and find the coverage report. Whereas coverageSourceDirs is used for giving the source set, The coverage should be reported in the reports.</li></ul><p><strong>The final step is to create the coverage report </strong>😁</p><ul><li>This will create an HTML report under <em>app/build/coverage-report/</em> which we can view and analyze.</li><li>One can mark enabled true if they want to report in that format and give a destination too for it.</li></ul><pre>reports {<br>  csv.enabled false<br>  xml.enabled false<br>  html {<br>    enabled true<br>    destination file(&quot;${project.buildDir}/coverage-report&quot;)<br>      }<br>  }</pre><h3>Final code for Single Module</h3><pre>--- app module build.gradle ---<br><br>appFileFilter = [&quot;**/example/network/&quot;,<br>                 &quot;**/example/repository/&quot;,<br>                 &quot;**/example/utils/NetworkUtils.*&quot;]<br>                 <br>appJavaFileTree = fileTree(dir: &quot;${project(&#39;:app:&#39;).getProject().buildDir}/intermediates/javac/Debug/classes&quot;, includes: appFileFilter)<br>appKotlinFileTree = fileTree(dir: &quot;${project(&#39;:app:&#39;).getProject().buildDir}/tmp/kotlin-classes/Debug&quot;, includes: appFileFilter)<br><br>afterEvaluate {<br><br>  task &quot;appNetworkCoverage&quot;(type: JacocoReport) {<br>        dependsOn test // Jacoco Requires to run test to get coverage report<br>        group = &quot;Coverage Report&quot;<br>        description = &quot;Generate coverage report of Network/*,repository/* and utils/NetworkUtils.kt&quot;<br>        classDirectories.from = files([appJavaFileTree], [appKotlinFileTree])<br>        executionData.from = file(&quot;${project.buildDir}/jacoco/testUnitTest.exec&quot;)<br><br>        def coverageSourceDirs = [&quot;src/main/java&quot;]<br><br>        sourceDirectories.setFrom(files(coverageSourceDirs))<br><br>        reports {<br>            csv.enabled false<br>            xml.enabled false<br>            html {<br>                enabled true<br>                destination file(&quot;${project.buildDir}/coverage-report&quot;)<br>            }<br>        }<br>    }<br>}</pre><p><strong>Command to get the coverage report:</strong></p><pre>$./gradlew Tasks   &lt;- View tasks<br><br>Coverage Report tasks<br>---------------------<br>appNetworkCoverage - Generate coverage report of Network/*,repository/* and utils/NetworkUtils.kt<br><br><br>$./gradlew appNetworkCoverage   &lt;- this runs the coverage report task</pre><p>Well, whats next?</p><ul><li>Well as said in the benefits of using jacoco we can get coverage for multi modules too that too being specific about which module we want to find.</li><li>To accomplish this will use something known as <strong>JacocoMerge</strong> , This will merge multiple <em>.exec</em> files to create a single <em>.exec</em> and give a single coverage report for all merged <em>.exec</em> files</li><li>To create a <em>.exec</em> file we can use the above <strong>Single Module </strong>Method</li><li>Let’s say we have two modules app and commons</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Z80kkcA4OTlbdG0HC8-BIQ.png" /></figure><ul><li>After merging multiple <em>.exec</em> file we need to use JacocoReport to create Coverage Report.</li><li>To create a coverage report we need to select an entry point, here I would choose commons and will generate the <em>.exec</em> file of commons first then the app, Then will merge both <em>.exec</em> files generated together into a single <em>.exec</em> file and get the coverage report of that single <em>.exec</em> file.</li></ul><blockquote>To create <strong>.exec</strong> file will use single module method on each module</blockquote><pre>---- commons gradle ----<br>apply from: &quot;$project.rootDir/tools/script-jacoco.gradle&quot; &lt;- Where Variables, and Merge Tasks would be declared<br><br>afterEvaluate {<br><br>  task &quot;commonsCovergae&quot; (type: JacocoReport) {<br>      dependsOn   test<br>      classDirectories.from = files([commonsJavaFileTree], [commonsKotlinFileTree])<br>      executionData.from = file(&quot;${project.buildDir}/jacoco/testDebugUnitTest.exec&quot;)<br><br>      def coverageSourceDirs = [&quot;src/main/java&quot;]<br><br>      sourceDirectories.setFrom(files(coverageSourceDirs))<br>      <br>      // opitional to have reports block in module level gradle if going for multi module coverage <br>      reports {<br>          csv.enabled false<br>          xml.enabled false<br>          html {<br>              enabled true<br>              destination file(&quot;${project.buildDir}/coverage-report&quot;)<br>          }<br>      }<br>  }<br>}<br><br>---- app gradle ----<br>apply from: &quot;$project.rootDir/tools/script-jacoco.gradle&quot; <br><br>afterEvaluate {<br>    task &quot;appCoverage&quot;(type: JacocoReport) {<br>        dependsOn test<br>        classDirectories.from = files([appJavaFileTree], [appKotlinFileTree])<br>        executionData.from = file(&quot;${project.buildDir}/jacoco/testDebugUnitTest.exec&quot;)<br>    <br>        def coverageSourceDirs = [&quot;src/main/java&quot;]<br>    <br>        sourceDirectories.setFrom(files(coverageSourceDirs))<br>      <br>        // opitional to have reports block in module level gradle if going for multi module coverage<br>        reports {<br>            csv.enabled false<br>            xml.enabled false<br>            html {<br>                enabled true<br>                destination file(&quot;${project.buildDir}/coverage-report&quot;)<br>        }<br>    }<br>}</pre><p>Here we can see there is a new file introduced that is <strong><em>script-jacoco.gradle</em></strong>, It holds the necessary file trees required for test coverage and tasks that are needed to generate merged reports.</p><pre>---- script-jacoco.gradle ----<br><br>afterEvaluate { project -&gt;<br>    coverageTest()<br>}<br><br>ext {<br>appFileFilter = [&quot;**/example/network/&quot;,<br>                 &quot;**/example/repository/&quot;,<br>                 &quot;**/example/utils/NetworkUtils.*&quot;]<br>                 <br>appJavaFileTree = fileTree(dir: &quot;${project(&#39;:app:&#39;).getProject().buildDir}/intermediates/javac/Debug/classes&quot;, includes: appFileFilter)<br>appKotlinFileTree = fileTree(dir: &quot;${project(&#39;:app:&#39;).getProject().buildDir}/tmp/kotlin-classes/Debug&quot;, includes: appFileFilter)<br> <br>// similarly for commonsFileTrees too <br><br>}<br>def coverageTest() {<br>  <br>  task &quot;appAndCommonsCoverage&quot;(type: JacocoReport) {<br>        dependsOn appAndCommonsMerge<br>        group = &quot;Coverage Report&quot;<br>        description = &quot;Generate coverage report for app and commons module&quot;<br><br>        classDirectories.from = files([appJavaFileTree], [appKotlinFileTree], [commonsJavaFileTree], [commonsKotlinFileTree])<br>        def coverageSourceDirs = [&quot;src/main/java&quot;]<br>        sourceDirectories.setFrom(files(coverageSourceDirs))<br>        executionData(file(&quot;${rootProject.buildDir}/jacoco/appCommonsMerge.exec&quot;)) &lt;- execute single .exec file inside root project build<br>        reports {<br>            csv.enabled false<br>            xml.enabled false<br>            html {<br>                enabled true<br>                destination file(&quot;${rootProject.buildDir}/jacoco/coverage-report&quot;)<br>            }<br>        }<br>    }<br>}<br><br>task &quot;appAndCommonsMerge&quot;(type: JacocoMerge) {<br>    dependsOn &#39;:app:appCoverage&#39;<br>    dependsOn &#39;:commons:commonsCovergae&#39;<br>    afterEvaluate {<br>        Project appProject = project(&#39;:app:&#39;).getProject()<br>        Project commonsProject = project(&#39;:commons:&#39;).getProject()<br>        def appJacocoCoverageFile = file(&quot;${appProject.buildDir}/jacoco/testDebugUnitTest.exec&quot;)  // &lt;-- get the first .exec file<br>        def commonsJacocoCoverageFile = file(&quot;${commonsProject.buildDir}/jacoco/testDebugUnitTest.exec&quot;). // &lt;-- get the second .exec file<br>        executionData(files(appJacocoCoverageFile, commonsJacocoCoverageFile)) // &lt;--- Merges the two .exec files in one<br>        destinationFile(file(&quot;${rootProject.buildDir}/jacoco/appCommonsMerge.exec&quot;)) // &lt;-- single .exec file with name appCommonsMerge.exec<br>    }<br>}</pre><p>The above piece of code will create a single coverage report for multi-module. The flow to create so would be like</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9qKNcsv0M6LH6vL1GJsmxA.png" /></figure><pre>$./gradlew appAndCommonsCoverage    (&lt;--call) </pre><p><strong>How it’s executed?</strong><br>Calling appAndCommonsCoverage will call appAndCommonsMerge since it depends on it to get executed first, But appAndCommonsMerge depends on 2 things</p><p>1. :app:appCoverage<br> 2. :commons:commonsCovergae</p><p>So those two tasks will be executed first and then the individual <em>.exec</em> file will be in the app and commons module.</p><p>Then appAndCommonsMerge will take that 2 <em>.exec</em> file and merge them in a single <em>.exec</em> file</p><p>Finally, appAndCommonsCoverage will execute the single <em>.exec</em> file and give the coverage report of it at the destination provided</p><p><strong>Conclusion:</strong><br>This is how one can find coverage for multimodule or single-module projects without spending a huge development time.</p><p>I hope this article will be helpful in designing your app. I would love to hear your comments/suggestions/corrections/questions!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=358bc9b251f6" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>