├── .buildscript └── deploy_snapshot.sh ├── .editorconfig ├── .github └── workflows │ ├── build.yml │ ├── publish-release.yml │ └── publish-snapshot.yml ├── .gitignore ├── CHANGELOG.md ├── LICENSE ├── README.md ├── build.gradle ├── gradle.properties ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── gradlew ├── gradlew.bat ├── settings.gradle └── src ├── main └── groovy │ └── com │ └── vanniktech │ └── android │ └── junit │ └── jacoco │ ├── GenerationPlugin.groovy │ ├── JunitJacocoExtension.groovy │ └── ReportConfig.groovy └── test └── groovy └── com └── vanniktech └── android └── junit └── jacoco ├── GenerationPluginSpec.groovy ├── GenerationTest.groovy ├── JunitJacocoExtensionTest.groovy └── ProjectHelper.groovy /.buildscript/deploy_snapshot.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | # 3 | # Deploy a jar, source jar, and javadoc jar to Sonatype's snapshot repo. 4 | # 5 | # Adapted from https://coderwall.com/p/9b_lfq and 6 | # http://benlimmer.com/2013/12/26/automatically-publish-javadoc-to-gh-pages-with-travis-ci/ and 7 | # https://github.com/JakeWharton/RxBinding/blob/master/.buildscript/deploy_snapshot.sh 8 | 9 | SLUG="vanniktech/gradle-android-junit-jacoco-plugin" 10 | JDK="oraclejdk8" 11 | BRANCH="master" 12 | 13 | set -e 14 | 15 | if [ "$TRAVIS_REPO_SLUG" != "$SLUG" ]; then 16 | echo "Skipping snapshot deployment: wrong repository. Expected '$SLUG' but was '$TRAVIS_REPO_SLUG'." 17 | elif [ "$TRAVIS_JDK_VERSION" != "$JDK" ]; then 18 | echo "Skipping snapshot deployment: wrong JDK. Expected '$JDK' but was '$TRAVIS_JDK_VERSION'." 19 | elif [ "$TRAVIS_PULL_REQUEST" != "false" ]; then 20 | echo "Skipping snapshot deployment: was pull request." 21 | elif [ "$TRAVIS_BRANCH" != "$BRANCH" ]; then 22 | echo "Skipping snapshot deployment: wrong branch. Expected '$BRANCH' but was '$TRAVIS_BRANCH'." 23 | else 24 | echo "Deploying snapshot..." 25 | ./gradlew uploadArchives 26 | echo "Snapshot deployed!" 27 | fi -------------------------------------------------------------------------------- /.editorconfig: -------------------------------------------------------------------------------- 1 | # EditorConfig helps developers define and maintain consistent 2 | # coding styles between different editors and IDEs 3 | # editorconfig.org 4 | 5 | # top-most EditorConfig file 6 | root = true 7 | 8 | [*] 9 | # Change these settings to your own preference 10 | indent_style = space 11 | indent_size = 2 12 | 13 | # We recommend you to keep these unchanged 14 | end_of_line = lf 15 | charset = utf-8 16 | trim_trailing_whitespace = true 17 | insert_final_newline = true 18 | -------------------------------------------------------------------------------- /.github/workflows/build.yml: -------------------------------------------------------------------------------- 1 | name: Build 2 | 3 | on: [push, pull_request] 4 | 5 | jobs: 6 | build: 7 | name: JDK ${{ matrix.java_version }} 8 | runs-on: ubuntu-latest 9 | 10 | strategy: 11 | matrix: 12 | java_version: [11] 13 | 14 | steps: 15 | - name: Checkout 16 | uses: actions/checkout@v2 17 | 18 | - name: Gradle Wrapper Validation 19 | uses: gradle/wrapper-validation-action@v1 20 | 21 | - name: Install JDK ${{ matrix.java_version }} 22 | uses: actions/setup-java@v1 23 | with: 24 | java-version: ${{ matrix.java_version }} 25 | 26 | - name: Build with Gradle 27 | run: ./gradlew build --stacktrace 28 | -------------------------------------------------------------------------------- /.github/workflows/publish-release.yml: -------------------------------------------------------------------------------- 1 | name: Publish Release 2 | 3 | on: 4 | push: 5 | tags: 6 | - '*' 7 | 8 | jobs: 9 | publish: 10 | 11 | runs-on: ubuntu-latest 12 | if: github.repository == 'vanniktech/gradle-android-junit-jacoco-plugin' 13 | 14 | steps: 15 | - name: Checkout 16 | uses: actions/checkout@v2 17 | 18 | - name: Install JDK 11 19 | uses: actions/setup-java@v1 20 | with: 21 | java-version: 11 22 | 23 | - name: Upload release 24 | run: ./gradlew publishAllPublicationsToMavenCentralRepository --no-daemon --no-parallel 25 | env: 26 | ORG_GRADLE_PROJECT_mavenCentralUsername: ${{ secrets.SONATYPE_NEXUS_USERNAME }} 27 | ORG_GRADLE_PROJECT_mavenCentralPassword: ${{ secrets.SONATYPE_NEXUS_PASSWORD }} 28 | ORG_GRADLE_PROJECT_signingInMemoryKey: ${{ secrets.SIGNING_PRIVATE_KEY }} 29 | ORG_GRADLE_PROJECT_signingInMemoryKeyPassword: ${{ secrets.SIGNING_PASSWORD }} 30 | 31 | - name: Publish release 32 | run: ./gradlew closeAndReleaseRepository --no-daemon --no-parallel 33 | env: 34 | ORG_GRADLE_PROJECT_mavenCentralUsername: ${{ secrets.SONATYPE_NEXUS_USERNAME }} 35 | ORG_GRADLE_PROJECT_mavenCentralPassword: ${{ secrets.SONATYPE_NEXUS_PASSWORD }} 36 | -------------------------------------------------------------------------------- /.github/workflows/publish-snapshot.yml: -------------------------------------------------------------------------------- 1 | name: Publish Snapshot 2 | 3 | on: 4 | push: 5 | branches: 6 | - master 7 | 8 | jobs: 9 | publish: 10 | 11 | runs-on: ubuntu-latest 12 | if: github.repository == 'vanniktech/gradle-android-junit-jacoco-plugin' 13 | 14 | steps: 15 | - name: Checkout 16 | uses: actions/checkout@v2 17 | 18 | - name: Install JDK 11 19 | uses: actions/setup-java@v1 20 | with: 21 | java-version: 11 22 | 23 | - name: Retrieve version 24 | run: | 25 | echo "VERSION_NAME=$(cat gradle.properties | grep -w "VERSION_NAME" | cut -d'=' -f2)" >> $GITHUB_ENV 26 | 27 | - name: Publish snapshot 28 | run: ./gradlew publishAllPublicationsToMavenCentralRepository --no-daemon --no-parallel 29 | if: endsWith(env.VERSION_NAME, '-SNAPSHOT') 30 | env: 31 | ORG_GRADLE_PROJECT_mavenCentralUsername: ${{ secrets.SONATYPE_NEXUS_USERNAME }} 32 | ORG_GRADLE_PROJECT_mavenCentralPassword: ${{ secrets.SONATYPE_NEXUS_PASSWORD }} 33 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | .gradle 2 | build/ 3 | 4 | # Ignore Gradle GUI config 5 | gradle-app.setting 6 | 7 | # Avoid ignoring Gradle wrapper jar file (.jar files are usually ignored) 8 | !gradle-wrapper.jar 9 | 10 | local.properties 11 | 12 | .idea/ 13 | *.iml 14 | 15 | *.DS_Store -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Change Log 2 | 3 | Version 0.17.0 *(In development)* 4 | --------------------------------- 5 | 6 | Version 0.16.0 *(2020-03-22)* 7 | ----------------------------- 8 | 9 | - "Plugin not found" when using snapshot version [\#159](https://github.com/vanniktech/gradle-android-junit-jacoco-plugin/issues/159) 10 | - Fix java classes being skipped in AGP \>= 3.4 [\#166](https://github.com/vanniktech/gradle-android-junit-jacoco-plugin/pull/166) ([jeppeman](https://github.com/jeppeman)) 11 | - Fix slow file traversal in configuration phase [\#163](https://github.com/vanniktech/gradle-android-junit-jacoco-plugin/pull/163) ([fo2rist](https://github.com/fo2rist)) 12 | - Fix "Could not get unknown property 'libraryVariants'" for dynamic-feature modules [\#160](https://github.com/vanniktech/gradle-android-junit-jacoco-plugin/pull/160) ([igorwojda](https://github.com/igorwojda)) 13 | - Add support for Android "dynamic-feature" module type [\#158](https://github.com/vanniktech/gradle-android-junit-jacoco-plugin/pull/158) ([igorwojda](https://github.com/igorwojda)) 14 | 15 | Version 0.15.0 *(2019-05-27)* 16 | ----------------------------- 17 | 18 | - Fixed "No signature of method: org.gradle.api.internal.file.CompositeFileCollection$1.setFrom\(\)" bug for mergeJacocoReports task. [\#157](https://github.com/vanniktech/gradle-android-junit-jacoco-plugin/pull/157) ([vasdeepika](https://github.com/vasdeepika)) 19 | - Fix Gradle 6.0 deprecation warnings. [\#155](https://github.com/vanniktech/gradle-android-junit-jacoco-plugin/pull/155) ([vanniktech](https://github.com/vanniktech)) 20 | 21 | Version 0.14.0 *(2019-04-30)* 22 | ----------------------------- 23 | 24 | - Update dependencies. [\#154](https://github.com/vanniktech/gradle-android-junit-jacoco-plugin/pull/154) ([vanniktech](https://github.com/vanniktech)) 25 | - Add support for Gradle 5 [\#153](https://github.com/vanniktech/gradle-android-junit-jacoco-plugin/pull/153) ([henriquenfaria](https://github.com/henriquenfaria)) 26 | - Fix StackOverflowError with Gradle 5.0 regarding FileCollection [\#151](https://github.com/vanniktech/gradle-android-junit-jacoco-plugin/pull/151) ([Laimiux](https://github.com/Laimiux)) 27 | - Cope with new Android DSL to configure includeNoLocationClasses [\#150](https://github.com/vanniktech/gradle-android-junit-jacoco-plugin/pull/150) ([aygalinc](https://github.com/aygalinc)) 28 | - Add support for kotlin multiplatform plugin [\#141](https://github.com/vanniktech/gradle-android-junit-jacoco-plugin/pull/141) ([henriquenfaria](https://github.com/henriquenfaria)) 29 | - Remove sudo: false from travis config. [\#135](https://github.com/vanniktech/gradle-android-junit-jacoco-plugin/pull/135) ([vanniktech](https://github.com/vanniktech)) 30 | - Don't run tests when creating the merged test coverage report. Instead it's required to run specific tests manually before. [\#134](https://github.com/vanniktech/gradle-android-junit-jacoco-plugin/pull/134) ([vRallev](https://github.com/vRallev)) 31 | 32 | Version 0.13.0 *(2018-10-11)* 33 | ----------------------------- 34 | 35 | - Update Gradle Maven Publish Plugin to 0.6.0 [\#132](https://github.com/vanniktech/gradle-android-junit-jacoco-plugin/pull/132) ([vanniktech](https://github.com/vanniktech)) 36 | - Integrate instrumentation tests [\#131](https://github.com/vanniktech/gradle-android-junit-jacoco-plugin/pull/131) ([vRallev](https://github.com/vRallev)) 37 | - Don't apply the plugin for Android test projects [\#130](https://github.com/vanniktech/gradle-android-junit-jacoco-plugin/pull/130) ([vRallev](https://github.com/vRallev)) 38 | - Use Jacoco 0.8.2 by default [\#129](https://github.com/vanniktech/gradle-android-junit-jacoco-plugin/pull/129) ([vRallev](https://github.com/vRallev)) 39 | - Reapply the Jacoco version after the project has been evaluated [\#128](https://github.com/vanniktech/gradle-android-junit-jacoco-plugin/pull/128) ([vRallev](https://github.com/vRallev)) 40 | - Update Plugin Publish Plugin to 0.10.0 [\#126](https://github.com/vanniktech/gradle-android-junit-jacoco-plugin/pull/126) ([vanniktech](https://github.com/vanniktech)) 41 | - Support all the Android / Java plugins. [\#124](https://github.com/vanniktech/gradle-android-junit-jacoco-plugin/pull/124) ([vanniktech](https://github.com/vanniktech)) 42 | 43 | Big thanks to Ralf for all of his work! 44 | 45 | Version 0.12.0 *(2018-06-30)* 46 | ----------------------------- 47 | 48 | - Add the new path for Java class files in newer Android Gradle Plugin … [\#122](https://github.com/vanniktech/gradle-android-junit-jacoco-plugin/pull/122) ([vRallev](https://github.com/vRallev)) 49 | - Fix id for Gradle Plugin that was added in \#118 [\#120](https://github.com/vanniktech/gradle-android-junit-jacoco-plugin/pull/120) ([vanniktech](https://github.com/vanniktech)) 50 | - Unify setup, improve a few things and bump versions. [\#118](https://github.com/vanniktech/gradle-android-junit-jacoco-plugin/pull/118) ([vanniktech](https://github.com/vanniktech)) 51 | - Use Gradle Maven Publish Plugin for publishing. [\#117](https://github.com/vanniktech/gradle-android-junit-jacoco-plugin/pull/117) ([vanniktech](https://github.com/vanniktech)) 52 | - Instant app support [\#111](https://github.com/vanniktech/gradle-android-junit-jacoco-plugin/pull/111) ([dazza5000](https://github.com/dazza5000)) 53 | 54 | Version 0.11.0 *(2017-12-10)* 55 | ----------------------------- 56 | 57 | - Only include main sources in the classes directory for Java projects. [\#105](https://github.com/vanniktech/gradle-android-junit-jacoco-plugin/pull/105) ([vanniktech](https://github.com/vanniktech)) 58 | - Allow ignoring the module path and name [\#103](https://github.com/vanniktech/gradle-android-junit-jacoco-plugin/pull/103) ([vRallev](https://github.com/vRallev)) 59 | - Ignore classes generated by the android-state library [\#102](https://github.com/vanniktech/gradle-android-junit-jacoco-plugin/pull/102) ([vRallev](https://github.com/vRallev)) 60 | - Add correct Kotlin class path [\#101](https://github.com/vanniktech/gradle-android-junit-jacoco-plugin/pull/101) ([vRallev](https://github.com/vRallev)) 61 | - Update Android License hash. [\#98](https://github.com/vanniktech/gradle-android-junit-jacoco-plugin/pull/98) ([vanniktech](https://github.com/vanniktech)) 62 | - Update plugin-publish-plugin [\#97](https://github.com/vanniktech/gradle-android-junit-jacoco-plugin/pull/97) ([timyates](https://github.com/timyates)) 63 | 64 | Version 0.10.0 *(2017-10-08)* 65 | ----------------------------- 66 | 67 | - Update JUnit Jacoco Gradle Plugin to 0.9.0 [\#96](https://github.com/vanniktech/gradle-android-junit-jacoco-plugin/pull/96) ([vanniktech](https://github.com/vanniktech)) 68 | - Generate csv reports [\#95](https://github.com/vanniktech/gradle-android-junit-jacoco-plugin/pull/95) ([alexrwegener](https://github.com/alexrwegener)) 69 | - Remove deprecated method calls [\#94](https://github.com/vanniktech/gradle-android-junit-jacoco-plugin/pull/94) ([vRallev](https://github.com/vRallev)) 70 | 71 | Version 0.9.0 *(2017-09-12)* 72 | ---------------------------- 73 | 74 | - Fix the class file location for the Android Gradle Plugin 3.0.0 [\#90](https://github.com/vanniktech/gradle-android-junit-jacoco-plugin/pull/90) ([vRallev](https://github.com/vRallev)) 75 | - Merged test code coverage report [\#89](https://github.com/vanniktech/gradle-android-junit-jacoco-plugin/pull/89) ([vRallev](https://github.com/vRallev)) 76 | - Autoexclude \*\_Factory classes that are generated by Dagger 2. [\#88](https://github.com/vanniktech/gradle-android-junit-jacoco-plugin/pull/88) ([vanniktech](https://github.com/vanniktech)) 77 | - Don't clean build again when deploying SNAPSHOTS. [\#86](https://github.com/vanniktech/gradle-android-junit-jacoco-plugin/pull/86) ([vanniktech](https://github.com/vanniktech)) 78 | - Update Jacoco Gradle Plugin to 0.8.0 [\#85](https://github.com/vanniktech/gradle-android-junit-jacoco-plugin/pull/85) ([vanniktech](https://github.com/vanniktech)) 79 | 80 | Version 0.8.0 *(2017-08-14)* 81 | ---------------------------- 82 | 83 | - Fix Jacoco generation for Java. [\#82](https://github.com/vanniktech/gradle-android-junit-jacoco-plugin/pull/82) ([vanniktech](https://github.com/vanniktech)) 84 | 85 | Version 0.7.0 *(2017-08-02)* 86 | ---------------------------- 87 | 88 | - Support popular JVM languages [\#75](https://github.com/vanniktech/gradle-android-junit-jacoco-plugin/pull/75) ([jaredsburrows](https://github.com/jaredsburrows)) 89 | - \[Tests\] - Add tests for GenerationPlugin [\#71](https://github.com/vanniktech/gradle-android-junit-jacoco-plugin/pull/71) ([jaredsburrows](https://github.com/jaredsburrows)) 90 | - Don't add jacoco tasks for ignored build variants [\#69](https://github.com/vanniktech/gradle-android-junit-jacoco-plugin/pull/69) ([passsy](https://github.com/passsy)) 91 | 92 | Version 0.6.0 *(2017-03-20)* 93 | ---------------------------- 94 | 95 | - Fix includeNoLocationClasses. [\#61](https://github.com/vanniktech/gradle-android-junit-jacoco-plugin/pull/61) ([vanniktech](https://github.com/vanniktech)) 96 | - Add a few more default excludes. [\#58](https://github.com/vanniktech/gradle-android-junit-jacoco-plugin/pull/58) ([vanniktech](https://github.com/vanniktech)) 97 | - Add extension for includeNoLocationClasses [\#55](https://github.com/vanniktech/gradle-android-junit-jacoco-plugin/pull/55) ([vanniktech](https://github.com/vanniktech)) 98 | - Adding AutoValue to exclusion list [\#54](https://github.com/vanniktech/gradle-android-junit-jacoco-plugin/pull/54) ([setheclark](https://github.com/setheclark)) 99 | - Added several exclusions when generating report. [\#41](https://github.com/vanniktech/gradle-android-junit-jacoco-plugin/pull/41) ([zsavely](https://github.com/zsavely)) 100 | 101 | Version 0.5.0 *(2016-07-17)* 102 | ---------------------------- 103 | 104 | - Add excludes to JunitJacoco extension [\#37](https://github.com/vanniktech/gradle-android-junit-jacoco-plugin/pull/37) ([vanniktech](https://github.com/vanniktech)) 105 | - Clean up tests [\#36](https://github.com/vanniktech/gradle-android-junit-jacoco-plugin/pull/36) ([vanniktech](https://github.com/vanniktech)) 106 | - Restore flavor iterations [\#34](https://github.com/vanniktech/gradle-android-junit-jacoco-plugin/pull/34) ([outlying](https://github.com/outlying)) - many thanks to him 107 | - Update to Gradle 2.14 [\#33](https://github.com/vanniktech/gradle-android-junit-jacoco-plugin/pull/33) ([vanniktech](https://github.com/vanniktech)) 108 | - Fix Travis after\_success. [\#32](https://github.com/vanniktech/gradle-android-junit-jacoco-plugin/pull/32) ([vanniktech](https://github.com/vanniktech)) 109 | - Update to Gradle 2.13 [\#31](https://github.com/vanniktech/gradle-android-junit-jacoco-plugin/pull/31) ([vanniktech](https://github.com/vanniktech)) 110 | - Add Codecov file [\#30](https://github.com/vanniktech/gradle-android-junit-jacoco-plugin/pull/30) ([vanniktech](https://github.com/vanniktech)) 111 | - Update Android Gradle Build Tools to 2.1.0 [\#29](https://github.com/vanniktech/gradle-android-junit-jacoco-plugin/pull/29) ([vanniktech](https://github.com/vanniktech)) 112 | - Add Codecov Coverage [\#26](https://github.com/vanniktech/gradle-android-junit-jacoco-plugin/pull/26) ([vanniktech](https://github.com/vanniktech)) 113 | 114 | Version 0.4.0 *(2016-04-10)* 115 | -------------------------------- 116 | 117 | - Add Single project support [\#25](https://github.com/vanniktech/gradle-android-junit-jacoco-plugin/pull/25) ([vanniktech](https://github.com/vanniktech)) 118 | 119 | Version 0.3.0 *(2016-03-23)* 120 | -------------------------------- 121 | 122 | - Remove merged report [\#24](https://github.com/vanniktech/OnActivityResult/pull/24) ([vanniktech](https://github.com/vanniktech)) 123 | - Add support for Java projects [\#24](https://github.com/vanniktech/OnActivityResult/pull/24) ([vanniktech](https://github.com/vanniktech)) 124 | - Add Android build variant specific Jacoco tasks [\#24](https://github.com/vanniktech/OnActivityResult/pull/24) ([vanniktech](https://github.com/vanniktech)) 125 | - Hook Jacoco tasks into check task [\#24](https://github.com/vanniktech/OnActivityResult/pull/24) ([vanniktech](https://github.com/vanniktech)) 126 | - Add some more excludes [\#21](https://github.com/vanniktech/gradle-android-junit-jacoco-plugin/pull/21) ([vanniktech](https://github.com/vanniktech)) 127 | 128 | **Note: Since tasks were removed and added please have a look at the [README](README.md) to get an overview of all the features of version 0.3.0** 129 | 130 | Version 0.2.0 *(2016-11-01)* 131 | ---------------------------- 132 | 133 | - Add merged report 134 | 135 | Version 0.1.1 *(2015-10-25)* 136 | ---------------------------- 137 | 138 | - Fix Jacoco version specification 139 | 140 | Version 0.1.0 *(2015-10-15)* 141 | ---------------------------- 142 | 143 | - Initial release 144 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | 203 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # gradle-android-junit-jacoco-plugin 2 | 3 | Gradle plugin that generates Jacoco reports from a Gradle Project. Android Application, Android Library, Kotlin and Java Plugins are supported by this plugin. When this plugin is applied it goes over every subproject and creates the corresponding Jacoco tasks. 4 | 5 | ### Android project 6 | 7 | *JVM Unit-Tests* 8 | - Task `jacocoTestReport` 9 | - Executes the `testUnitTest` task before 10 | - Gets executed when the `check` task is executed 11 | - Generated Jacoco reports can be found under `build/reports/jacoco//`. 12 | 13 | *Instrumented tests* 14 | - Task `combinedTestReport` 15 | - Executes the `testUnitTest` and `createCoverageReports` tasks before (JVM and instrumented tests) 16 | - Gets executed when the `check` task is executed 17 | - Generated Jacoco reports can be found under `build/reports/jacocoCombined//`. 18 | Note that this task is only generated, if you set `testCoverageEnabled = true` for your [build type](https://google.github.io/android-gradle-dsl/current/com.android.build.gradle.internal.dsl.BuildType.html#com.android.build.gradle.internal.dsl.BuildType:testCoverageEnabled), e.g. 19 | ```groovy 20 | android { 21 | buildTypes { 22 | debug { 23 | testCoverageEnabled true 24 | } 25 | } 26 | } 27 | ``` 28 | 29 | Where `` is usually `debug` & `release` unless additional build types where specified. 30 | `` is optional and will be ignored if not specified. 31 | 32 | For instance when having `debug` & `release` build types and no flavors the following tasks would be created: `jacocoTestReportDebug` and `jacocoTestReportRelease`. 33 | 34 | When having `debug` & `release` build types and `red` & `blue` flavors the following tasks would be created: `jacocoTestReportRedDebug`, `jacocoTestReportBlueDebug`, `jacocoTestReportRedRelease` and `jacocoTestReportBlueRelease`. 35 | 36 | ### Java project 37 | 38 | - Task `jacocoTestReport` 39 | - Executes the `test` task before 40 | - Gets executed when the `check` task is executed 41 | - Generated Jacoco reports can be found under `build/reports/jacoco/`. 42 | 43 | In addition the plugin generates `mergeJacocoReports` & `jacocoTestReportMerged` tasks. 44 | 45 | `mergeJacocoReports` will merge all of the jacoco reports together. 46 | 47 | `jacocoTestReportMerged` will output an xml and html file for the merged report. 48 | 49 | Works with the latest Gradle Android Tools version 3.4.0. This plugin is compiled using Java 7 hence you also need Java 7 in order to use it. 50 | 51 | # Set up 52 | 53 | **root/build.gradle** 54 | 55 | ```gradle 56 | buildscript { 57 | repositories { 58 | mavenCentral() 59 | } 60 | dependencies { 61 | classpath "com.vanniktech:gradle-android-junit-jacoco-plugin:0.16.0" 62 | } 63 | } 64 | 65 | apply plugin: "com.vanniktech.android.junit.jacoco" 66 | ``` 67 | 68 | Information: [This plugin is also available on Gradle plugins](https://plugins.gradle.org/plugin/com.vanniktech.android.junit.jacoco) 69 | 70 | ### Snapshot 71 | 72 | ```gradle 73 | buildscript { 74 | repositories { 75 | maven { url "https://oss.sonatype.org/content/repositories/snapshots" } 76 | } 77 | dependencies { 78 | classpath "com.vanniktech:gradle-android-junit-jacoco-plugin:0.17.0-SNAPSHOT" 79 | } 80 | } 81 | 82 | apply plugin: "com.vanniktech.android.junit.jacoco" 83 | ``` 84 | 85 | ### Configuration 86 | 87 | Those are all available configurations - shown with default values and their types. More information can be found in the [Java Documentation of the Extension](src/main/groovy/com/vanniktech/android/junit/jacoco/JunitJacocoExtension.groovy). 88 | 89 | ```groovy 90 | junitJacoco { 91 | jacocoVersion = '0.8.7' // type String 92 | ignoreProjects = [] // type String array 93 | excludes // type String List 94 | includeNoLocationClasses = false // type boolean 95 | includeInstrumentationCoverageInMergedReport = false // type boolean 96 | xml.enabled = true 97 | csv.enabled = true 98 | html.enabled = true 99 | } 100 | ``` 101 | 102 | # License 103 | 104 | Copyright (C) 2015 Vanniktech - Niklas Baudy 105 | 106 | Licensed under the Apache License, Version 2.0 107 | -------------------------------------------------------------------------------- /build.gradle: -------------------------------------------------------------------------------- 1 | import org.gradle.api.internal.classpath.ModuleRegistry 2 | import org.gradle.api.internal.project.ProjectInternal 3 | 4 | buildscript { 5 | repositories { 6 | mavenCentral() 7 | google() 8 | gradlePluginPortal() 9 | } 10 | 11 | dependencies { 12 | classpath 'com.gradle.publish:plugin-publish-plugin:0.10.1' 13 | classpath 'com.vanniktech:gradle-android-junit-jacoco-plugin:0.16.0' 14 | classpath 'com.vanniktech:gradle-maven-publish-plugin:0.16.0' 15 | } 16 | } 17 | 18 | apply plugin: 'groovy' 19 | apply plugin: 'java-library' 20 | apply plugin: 'java-gradle-plugin' 21 | apply plugin: 'com.vanniktech.android.junit.jacoco' 22 | apply plugin: "com.vanniktech.maven.publish" 23 | apply plugin: 'com.gradle.plugin-publish' 24 | 25 | gradlePlugin { 26 | plugins { 27 | androidJUnitJacocoPlugin { 28 | id = 'com.vanniktech.android.junit.jacoco' 29 | implementationClass = 'com.vanniktech.android.junit.jacoco.GenerationPlugin' 30 | } 31 | } 32 | } 33 | 34 | repositories { 35 | mavenCentral() 36 | google() 37 | jcenter() 38 | } 39 | 40 | dependencies { 41 | api gradleApi() 42 | api localGroovy() 43 | 44 | compileOnly 'com.android.tools.build:gradle:7.1.2' 45 | 46 | testImplementation 'com.android.tools.build:gradle:7.1.2' 47 | testImplementation 'org.jetbrains.kotlin:kotlin-gradle-plugin:1.6.10' 48 | testImplementation 'junit:junit:4.13' 49 | testImplementation 'org.spockframework:spock-core:2.2-M1-groovy-3.0', { exclude module: "groovy-all" } // Use localGroovy() 50 | 51 | // https://github.com/gradle/gradle/issues/16774#issuecomment-893493869 52 | def toolingApiBuildersJar = (project as ProjectInternal).services.get(ModuleRegistry.class) 53 | .getModule("gradle-tooling-api-builders") 54 | .classpath 55 | .asFiles 56 | .first() 57 | testRuntimeOnly(files(toolingApiBuildersJar)) 58 | } 59 | 60 | sourceCompatibility = JavaVersion.VERSION_1_8 61 | 62 | pluginBundle { 63 | website = POM_URL 64 | vcsUrl = POM_SCM_URL 65 | 66 | plugins { 67 | androidJUnitJacocoPlugin { 68 | displayName = POM_NAME 69 | tags = ['gradle', 'android', 'jacoco', 'app module', 'library module', 'junit', 'unit', 'testing', 'coverage'] 70 | description = POM_DESCRIPTION 71 | } 72 | } 73 | } 74 | 75 | tasks.withType(Test).configureEach { 76 | testLogging { 77 | testLogging.exceptionFormat = 'full' 78 | } 79 | } 80 | 81 | wrapper { 82 | gradleVersion = '7.4' 83 | distributionType = Wrapper.DistributionType.ALL 84 | } 85 | -------------------------------------------------------------------------------- /gradle.properties: -------------------------------------------------------------------------------- 1 | GROUP=com.vanniktech 2 | VERSION_NAME=0.17.0-SNAPSHOT 3 | 4 | POM_ARTIFACT_ID=gradle-android-junit-jacoco-plugin 5 | POM_NAME=Gradle Android Jacoco Plugin 6 | POM_PACKAGING=jar 7 | 8 | POM_DESCRIPTION=Gradle plugin that generates Jacoco reports from an Android Gradle Project. 9 | POM_INCEPTION_YEAR=2015 10 | 11 | POM_URL=http://github.com/vanniktech/gradle-android-junit-jacoco-plugin/ 12 | POM_SCM_URL=http://github.com/vanniktech/gradle-android-junit-jacoco-plugin/ 13 | POM_SCM_CONNECTION=scm:git:git://github.com/vanniktech/gradle-android-junit-jacoco-plugin.git 14 | POM_SCM_DEV_CONNECTION=scm:git:ssh://git@github.com/vanniktech/gradle-android-junit-jacoco-plugin.git 15 | 16 | POM_LICENCE_NAME=The Apache Software License, Version 2.0 17 | POM_LICENCE_URL=http://www.apache.org/licenses/LICENSE-2.0.txt 18 | POM_LICENCE_DIST=repo 19 | 20 | POM_DEVELOPER_ID=vanniktech 21 | POM_DEVELOPER_NAME=Niklas Baudy -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/vanniktech/gradle-android-junit-jacoco-plugin/58c9165726e2cf523b1eacfdc9b4558a9205887e/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-7.4-all.zip 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists 6 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | # 4 | # Copyright © 2015-2021 the original authors. 5 | # 6 | # Licensed under the Apache License, Version 2.0 (the "License"); 7 | # you may not use this file except in compliance with the License. 8 | # You may obtain a copy of the License at 9 | # 10 | # https://www.apache.org/licenses/LICENSE-2.0 11 | # 12 | # Unless required by applicable law or agreed to in writing, software 13 | # distributed under the License is distributed on an "AS IS" BASIS, 14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | # See the License for the specific language governing permissions and 16 | # limitations under the License. 17 | # 18 | 19 | ############################################################################## 20 | # 21 | # Gradle start up script for POSIX generated by Gradle. 22 | # 23 | # Important for running: 24 | # 25 | # (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is 26 | # noncompliant, but you have some other compliant shell such as ksh or 27 | # bash, then to run this script, type that shell name before the whole 28 | # command line, like: 29 | # 30 | # ksh Gradle 31 | # 32 | # Busybox and similar reduced shells will NOT work, because this script 33 | # requires all of these POSIX shell features: 34 | # * functions; 35 | # * expansions «$var», «${var}», «${var:-default}», «${var+SET}», 36 | # «${var#prefix}», «${var%suffix}», and «$( cmd )»; 37 | # * compound commands having a testable exit status, especially «case»; 38 | # * various built-in commands including «command», «set», and «ulimit». 39 | # 40 | # Important for patching: 41 | # 42 | # (2) This script targets any POSIX shell, so it avoids extensions provided 43 | # by Bash, Ksh, etc; in particular arrays are avoided. 44 | # 45 | # The "traditional" practice of packing multiple parameters into a 46 | # space-separated string is a well documented source of bugs and security 47 | # problems, so this is (mostly) avoided, by progressively accumulating 48 | # options in "$@", and eventually passing that to Java. 49 | # 50 | # Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, 51 | # and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; 52 | # see the in-line comments for details. 53 | # 54 | # There are tweaks for specific operating systems such as AIX, CygWin, 55 | # Darwin, MinGW, and NonStop. 56 | # 57 | # (3) This script is generated from the Groovy template 58 | # https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt 59 | # within the Gradle project. 60 | # 61 | # You can find Gradle at https://github.com/gradle/gradle/. 62 | # 63 | ############################################################################## 64 | 65 | # Attempt to set APP_HOME 66 | 67 | # Resolve links: $0 may be a link 68 | app_path=$0 69 | 70 | # Need this for daisy-chained symlinks. 71 | while 72 | APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path 73 | [ -h "$app_path" ] 74 | do 75 | ls=$( ls -ld "$app_path" ) 76 | link=${ls#*' -> '} 77 | case $link in #( 78 | /*) app_path=$link ;; #( 79 | *) app_path=$APP_HOME$link ;; 80 | esac 81 | done 82 | 83 | APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit 84 | 85 | APP_NAME="Gradle" 86 | APP_BASE_NAME=${0##*/} 87 | 88 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 89 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' 90 | 91 | # Use the maximum available, or set MAX_FD != -1 to use that value. 92 | MAX_FD=maximum 93 | 94 | warn () { 95 | echo "$*" 96 | } >&2 97 | 98 | die () { 99 | echo 100 | echo "$*" 101 | echo 102 | exit 1 103 | } >&2 104 | 105 | # OS specific support (must be 'true' or 'false'). 106 | cygwin=false 107 | msys=false 108 | darwin=false 109 | nonstop=false 110 | case "$( uname )" in #( 111 | CYGWIN* ) cygwin=true ;; #( 112 | Darwin* ) darwin=true ;; #( 113 | MSYS* | MINGW* ) msys=true ;; #( 114 | NONSTOP* ) nonstop=true ;; 115 | esac 116 | 117 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 118 | 119 | 120 | # Determine the Java command to use to start the JVM. 121 | if [ -n "$JAVA_HOME" ] ; then 122 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 123 | # IBM's JDK on AIX uses strange locations for the executables 124 | JAVACMD=$JAVA_HOME/jre/sh/java 125 | else 126 | JAVACMD=$JAVA_HOME/bin/java 127 | fi 128 | if [ ! -x "$JAVACMD" ] ; then 129 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 130 | 131 | Please set the JAVA_HOME variable in your environment to match the 132 | location of your Java installation." 133 | fi 134 | else 135 | JAVACMD=java 136 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 137 | 138 | Please set the JAVA_HOME variable in your environment to match the 139 | location of your Java installation." 140 | fi 141 | 142 | # Increase the maximum file descriptors if we can. 143 | if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then 144 | case $MAX_FD in #( 145 | max*) 146 | MAX_FD=$( ulimit -H -n ) || 147 | warn "Could not query maximum file descriptor limit" 148 | esac 149 | case $MAX_FD in #( 150 | '' | soft) :;; #( 151 | *) 152 | ulimit -n "$MAX_FD" || 153 | warn "Could not set maximum file descriptor limit to $MAX_FD" 154 | esac 155 | fi 156 | 157 | # Collect all arguments for the java command, stacking in reverse order: 158 | # * args from the command line 159 | # * the main class name 160 | # * -classpath 161 | # * -D...appname settings 162 | # * --module-path (only if needed) 163 | # * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. 164 | 165 | # For Cygwin or MSYS, switch paths to Windows format before running java 166 | if "$cygwin" || "$msys" ; then 167 | APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) 168 | CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) 169 | 170 | JAVACMD=$( cygpath --unix "$JAVACMD" ) 171 | 172 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 173 | for arg do 174 | if 175 | case $arg in #( 176 | -*) false ;; # don't mess with options #( 177 | /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath 178 | [ -e "$t" ] ;; #( 179 | *) false ;; 180 | esac 181 | then 182 | arg=$( cygpath --path --ignore --mixed "$arg" ) 183 | fi 184 | # Roll the args list around exactly as many times as the number of 185 | # args, so each arg winds up back in the position where it started, but 186 | # possibly modified. 187 | # 188 | # NB: a `for` loop captures its iteration list before it begins, so 189 | # changing the positional parameters here affects neither the number of 190 | # iterations, nor the values presented in `arg`. 191 | shift # remove old arg 192 | set -- "$@" "$arg" # push replacement arg 193 | done 194 | fi 195 | 196 | # Collect all arguments for the java command; 197 | # * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of 198 | # shell script including quotes and variable substitutions, so put them in 199 | # double quotes to make sure that they get re-expanded; and 200 | # * put everything else in single quotes, so that it's not re-expanded. 201 | 202 | set -- \ 203 | "-Dorg.gradle.appname=$APP_BASE_NAME" \ 204 | -classpath "$CLASSPATH" \ 205 | org.gradle.wrapper.GradleWrapperMain \ 206 | "$@" 207 | 208 | # Use "xargs" to parse quoted args. 209 | # 210 | # With -n1 it outputs one arg per line, with the quotes and backslashes removed. 211 | # 212 | # In Bash we could simply go: 213 | # 214 | # readarray ARGS < <( xargs -n1 <<<"$var" ) && 215 | # set -- "${ARGS[@]}" "$@" 216 | # 217 | # but POSIX shell has neither arrays nor command substitution, so instead we 218 | # post-process each arg (as a line of input to sed) to backslash-escape any 219 | # character that might be a shell metacharacter, then use eval to reverse 220 | # that process (while maintaining the separation between arguments), and wrap 221 | # the whole thing up as a single "set" statement. 222 | # 223 | # This will of course break if any of these variables contains a newline or 224 | # an unmatched quote. 225 | # 226 | 227 | eval "set -- $( 228 | printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | 229 | xargs -n1 | 230 | sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | 231 | tr '\n' ' ' 232 | )" '"$@"' 233 | 234 | exec "$JAVACMD" "$@" 235 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @rem 2 | @rem Copyright 2015 the original author or authors. 3 | @rem 4 | @rem Licensed under the Apache License, Version 2.0 (the "License"); 5 | @rem you may not use this file except in compliance with the License. 6 | @rem You may obtain a copy of the License at 7 | @rem 8 | @rem https://www.apache.org/licenses/LICENSE-2.0 9 | @rem 10 | @rem Unless required by applicable law or agreed to in writing, software 11 | @rem distributed under the License is distributed on an "AS IS" BASIS, 12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | @rem See the License for the specific language governing permissions and 14 | @rem limitations under the License. 15 | @rem 16 | 17 | @if "%DEBUG%" == "" @echo off 18 | @rem ########################################################################## 19 | @rem 20 | @rem Gradle startup script for Windows 21 | @rem 22 | @rem ########################################################################## 23 | 24 | @rem Set local scope for the variables with windows NT shell 25 | if "%OS%"=="Windows_NT" setlocal 26 | 27 | set DIRNAME=%~dp0 28 | if "%DIRNAME%" == "" set DIRNAME=. 29 | set APP_BASE_NAME=%~n0 30 | set APP_HOME=%DIRNAME% 31 | 32 | @rem Resolve any "." and ".." in APP_HOME to make it shorter. 33 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi 34 | 35 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 36 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" 37 | 38 | @rem Find java.exe 39 | if defined JAVA_HOME goto findJavaFromJavaHome 40 | 41 | set JAVA_EXE=java.exe 42 | %JAVA_EXE% -version >NUL 2>&1 43 | if "%ERRORLEVEL%" == "0" goto execute 44 | 45 | echo. 46 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 47 | echo. 48 | echo Please set the JAVA_HOME variable in your environment to match the 49 | echo location of your Java installation. 50 | 51 | goto fail 52 | 53 | :findJavaFromJavaHome 54 | set JAVA_HOME=%JAVA_HOME:"=% 55 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 56 | 57 | if exist "%JAVA_EXE%" goto execute 58 | 59 | echo. 60 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 61 | echo. 62 | echo Please set the JAVA_HOME variable in your environment to match the 63 | echo location of your Java installation. 64 | 65 | goto fail 66 | 67 | :execute 68 | @rem Setup the command line 69 | 70 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 71 | 72 | 73 | @rem Execute Gradle 74 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* 75 | 76 | :end 77 | @rem End local scope for the variables with windows NT shell 78 | if "%ERRORLEVEL%"=="0" goto mainEnd 79 | 80 | :fail 81 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 82 | rem the _cmd.exe /c_ return code! 83 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 84 | exit /b 1 85 | 86 | :mainEnd 87 | if "%OS%"=="Windows_NT" endlocal 88 | 89 | :omega 90 | -------------------------------------------------------------------------------- /settings.gradle: -------------------------------------------------------------------------------- 1 | rootProject.name = 'gradle-android-junit-jacoco-plugin' -------------------------------------------------------------------------------- /src/main/groovy/com/vanniktech/android/junit/jacoco/GenerationPlugin.groovy: -------------------------------------------------------------------------------- 1 | package com.vanniktech.android.junit.jacoco 2 | 3 | import com.android.build.gradle.api.BaseVariant 4 | import org.gradle.api.Plugin 5 | import org.gradle.api.Project 6 | import org.gradle.api.tasks.testing.Test 7 | import org.gradle.testing.jacoco.tasks.JacocoMerge 8 | import org.gradle.testing.jacoco.tasks.JacocoReport 9 | 10 | class GenerationPlugin implements Plugin { 11 | @Override 12 | void apply(final Project rootProject) { 13 | rootProject.extensions.create('junitJacoco', JunitJacocoExtension) 14 | 15 | final def hasSubProjects = rootProject.subprojects.size() > 0 16 | 17 | if (hasSubProjects) { 18 | final def (JacocoMerge mergeTask, JacocoReport mergedReportTask) = addJacocoMergeToRootProject(rootProject, rootProject.junitJacoco) 19 | 20 | rootProject.subprojects { subProject -> 21 | afterEvaluate { 22 | final def extension = rootProject.junitJacoco 23 | addJacoco(subProject, extension, mergeTask, mergedReportTask) 24 | } 25 | } 26 | } else { 27 | rootProject.afterEvaluate { 28 | final def extension = rootProject.junitJacoco 29 | 30 | addJacoco(rootProject, extension) 31 | } 32 | } 33 | } 34 | 35 | protected static boolean addJacoco(final Project subProject, final JunitJacocoExtension extension) { 36 | return addJacoco(subProject, extension, null, null) 37 | } 38 | 39 | protected static boolean addJacoco(final Project subProject, final JunitJacocoExtension extension, JacocoMerge mergeTask, JacocoReport mergedReportTask) { 40 | if (!shouldIgnore(subProject, extension)) { 41 | if (isAndroidProject(subProject)) { 42 | return addJacocoAndroid(subProject, extension, mergeTask, mergedReportTask) 43 | } else if (isJavaProject(subProject) || isKotlinMultiplatform(subProject)) { 44 | return addJacocoJava(subProject, extension, mergeTask, mergedReportTask) 45 | } 46 | } 47 | 48 | return false 49 | } 50 | 51 | private static boolean addJacocoJava(final Project subProject, final JunitJacocoExtension extension, JacocoMerge mergeTask, JacocoReport mergedReportTask) { 52 | subProject.plugins.apply('jacoco') 53 | 54 | subProject.jacoco { 55 | toolVersion extension.jacocoVersion 56 | } 57 | 58 | subProject.jacocoTestReport { 59 | dependsOn 'test' 60 | 61 | group = 'Reporting' 62 | description = 'Generate Jacoco coverage reports.' 63 | 64 | reports { 65 | xml.enabled = extension.xml.enabled 66 | csv.enabled = extension.csv.enabled 67 | html.enabled = extension.html.enabled 68 | } 69 | 70 | getClassDirectories().from(subProject.fileTree( 71 | dir: subProject.buildDir, 72 | includes: ['**/classes/**/main/**'], 73 | excludes: getExcludes(extension) 74 | )) 75 | 76 | final def coverageSourceDirs = [ 77 | 'src/main/clojure', 78 | 'src/main/groovy', 79 | 'src/main/java', 80 | 'src/main/kotlin', 81 | 'src/main/scala' 82 | ] 83 | 84 | getAdditionalSourceDirs().from(subProject.files(coverageSourceDirs)) 85 | getSourceDirectories().from(subProject.files(coverageSourceDirs)) 86 | if (isKotlinMultiplatform(subProject)) { 87 | getExecutionData().from(subProject.files(subProject.files("${subProject.buildDir}/jacoco/jvmTest.exec"))) 88 | } else { 89 | getExecutionData().from(subProject.files(subProject.files("${subProject.buildDir}/jacoco/test.exec"))) 90 | } 91 | 92 | if (mergeTask != null) { 93 | mergeTask.executionData.setFrom(executionData.files + mergeTask.executionData.files) 94 | } 95 | if (mergedReportTask != null) { 96 | mergedReportTask.classDirectories.setFrom(classDirectories.getFrom() + mergedReportTask.classDirectories.getFrom()) 97 | mergedReportTask.additionalSourceDirs.setFrom(additionalSourceDirs.getFrom() + mergedReportTask.additionalSourceDirs.getFrom()) 98 | mergedReportTask.sourceDirectories.setFrom(sourceDirectories.getFrom() + mergedReportTask.sourceDirectories.getFrom()) 99 | } 100 | } 101 | 102 | subProject.check.dependsOn 'jacocoTestReport' 103 | return true 104 | } 105 | 106 | private static boolean addJacocoAndroid(final Project subProject, final JunitJacocoExtension extension, JacocoMerge mergeTask, JacocoReport mergedReportTask) { 107 | subProject.plugins.apply('jacoco') 108 | 109 | subProject.jacoco { 110 | toolVersion extension.jacocoVersion 111 | } 112 | 113 | subProject.tasks.withType(Test).configureEach { 114 | it.jacoco.includeNoLocationClasses = extension.includeNoLocationClasses 115 | } 116 | 117 | subProject.android.jacoco.version = extension.jacocoVersion 118 | 119 | Collection variants = [] 120 | if (isAndroidApplication(subProject) || isAndroidDynamicFeature(subProject)) { 121 | variants = subProject.android.applicationVariants 122 | } else if (isAndroidLibrary(subProject)) { 123 | // FeatureExtension extends LibraryExtension 124 | variants = subProject.android.libraryVariants 125 | } else { 126 | // test plugin or something else 127 | return false 128 | } 129 | 130 | variants.all { variant -> 131 | def productFlavorName = variant.getFlavorName() 132 | def buildType = variant.getBuildType() 133 | def buildTypeName = buildType.name 134 | 135 | def sourceName, sourcePath 136 | if (!productFlavorName) { 137 | sourceName = sourcePath = "${buildTypeName}" 138 | } else { 139 | sourceName = "${productFlavorName}${buildTypeName.capitalize()}" 140 | sourcePath = "${productFlavorName}/${buildTypeName}" 141 | } 142 | 143 | final def jvmTaskName = "jacocoTestReport${sourceName.capitalize()}" 144 | final def combinedTaskName = "combinedTestReport${sourceName.capitalize()}" 145 | 146 | final def jvmTestTaskName = "test${sourceName.capitalize()}UnitTest" 147 | final def instrumentationTestTaskName = "create${sourceName.capitalize()}CoverageReport" 148 | 149 | addJacocoTask(false, subProject, extension, mergeTask, mergedReportTask, jvmTaskName, 150 | jvmTestTaskName, instrumentationTestTaskName, sourceName, sourcePath, productFlavorName, buildTypeName) 151 | 152 | if (buildType.testCoverageEnabled) { 153 | addJacocoTask(true, subProject, extension, mergeTask, mergedReportTask, combinedTaskName, 154 | jvmTestTaskName, instrumentationTestTaskName, sourceName, sourcePath, productFlavorName, buildTypeName) 155 | } 156 | } 157 | 158 | return true 159 | } 160 | 161 | private static void addJacocoTask(final boolean combined, final Project subProject, final JunitJacocoExtension extension, 162 | JacocoMerge mergeTask, JacocoReport mergedReportTask, final String taskName, 163 | final String jvmTestTaskName, final String instrumentationTestTaskName, final String sourceName, 164 | final String sourcePath, final String productFlavorName, final String buildTypeName) { 165 | def destinationDir 166 | if (combined) { 167 | destinationDir = "${subProject.buildDir}/reports/jacocoCombined" 168 | } else { 169 | destinationDir = "${subProject.buildDir}/reports/jacoco" 170 | } 171 | 172 | subProject.task(taskName, type: JacocoReport) { 173 | group = 'Reporting' 174 | description = "Generate Jacoco coverage reports after running ${sourceName} tests." 175 | 176 | if (combined) { 177 | dependsOn jvmTestTaskName, instrumentationTestTaskName 178 | } else { 179 | dependsOn jvmTestTaskName 180 | } 181 | 182 | reports { 183 | xml { 184 | enabled = extension.xml.enabled 185 | destination subProject.file("$destinationDir/${sourceName}/jacoco.xml") 186 | } 187 | csv { 188 | enabled = extension.csv.enabled 189 | destination subProject.file("$destinationDir/${sourceName}/jacoco.csv") 190 | } 191 | html { 192 | enabled = extension.html.enabled 193 | destination subProject.file("$destinationDir/${sourceName}") 194 | } 195 | } 196 | 197 | def classPaths = [ 198 | "**/intermediates/classes/${sourcePath}/**", 199 | "**/intermediates/javac/${sourceName}/*/classes/**", // Android Gradle Plugin 3.2.x support. 200 | "**/intermediates/javac/${sourceName}/classes/**" // Android Gradle Plugin 3.4 and 3.5 support. 201 | ] 202 | 203 | if (isKotlinAndroid(subProject) || isKotlinMultiplatform(subProject)) { 204 | classPaths << "**/tmp/kotlin-classes/${sourcePath}/**" 205 | if (productFlavorName) { 206 | classPaths << "**/tmp/kotlin-classes/${productFlavorName}${buildTypeName.capitalize()}/**" 207 | } 208 | } 209 | 210 | getClassDirectories().from(subProject.fileTree( 211 | dir: subProject.buildDir, 212 | includes: classPaths, 213 | excludes: getExcludes(extension) 214 | )) 215 | 216 | final def coverageSourceDirs = [ 217 | "src/main/clojure", 218 | "src/main/groovy", 219 | "src/main/java", 220 | "src/main/kotlin", 221 | "src/main/scala", 222 | "src/$buildTypeName/clojure", 223 | "src/$buildTypeName/groovy", 224 | "src/$buildTypeName/java", 225 | "src/$buildTypeName/kotlin", 226 | "src/$buildTypeName/scala" 227 | ] 228 | 229 | if (productFlavorName) { 230 | coverageSourceDirs.add("src/$productFlavorName/clojure") 231 | coverageSourceDirs.add("src/$productFlavorName/groovy") 232 | coverageSourceDirs.add("src/$productFlavorName/java") 233 | coverageSourceDirs.add("src/$productFlavorName/kotlin") 234 | coverageSourceDirs.add("src/$productFlavorName/scala") 235 | } 236 | 237 | getAdditionalSourceDirs().from(subProject.files(coverageSourceDirs)) 238 | getSourceDirectories().from(subProject.files(coverageSourceDirs)) 239 | getExecutionData().from(subProject.files("${subProject.buildDir}/jacoco/${jvmTestTaskName}.exec")) 240 | 241 | if (combined) { 242 | // add instrumentation coverage execution data 243 | doFirst { 244 | def instrumentationTestCoverageDirs = subProject.fileTree("${subProject.buildDir}/outputs/code_coverage") 245 | .matching { include "**/*.ec" } 246 | def allCodeCoverageFiles = instrumentationTestCoverageDirs.files + executionData.files 247 | subProject.logger.with { 248 | info("using following code coverage files for ${taskName}") 249 | allCodeCoverageFiles.each { coverageFile -> 250 | info(coverageFile.path) 251 | } 252 | } 253 | executionData.setFrom(allCodeCoverageFiles) 254 | } 255 | } 256 | 257 | // add if true in extension or for the unit test Jacoco task 258 | def addToMergeTask = !combined || extension.includeInstrumentationCoverageInMergedReport 259 | 260 | if (mergeTask != null && addToMergeTask) { 261 | mergeTask.executionData.setFrom(executionData.files + mergeTask.executionData.files) 262 | } 263 | if (mergedReportTask != null && addToMergeTask) { 264 | mergedReportTask.classDirectories.setFrom(classDirectories.getFrom() + mergedReportTask.classDirectories.getFrom()) 265 | mergedReportTask.additionalSourceDirs.setFrom(additionalSourceDirs.getFrom() + mergedReportTask.additionalSourceDirs.getFrom()) 266 | mergedReportTask.sourceDirectories.setFrom(sourceDirectories.getFrom() + mergedReportTask.sourceDirectories.getFrom()) 267 | } 268 | } 269 | 270 | subProject.check.dependsOn "${taskName}" 271 | } 272 | 273 | protected static addJacocoMergeToRootProject(final Project project, final JunitJacocoExtension extension) { 274 | project.plugins.apply('jacoco') 275 | 276 | project.afterEvaluate { 277 | // Apply the Jacoco version after evaluating the project so that the extension could be configured 278 | project.jacoco { 279 | toolVersion extension.jacocoVersion 280 | } 281 | } 282 | 283 | def mergeTask = project.task("mergeJacocoReports", type: JacocoMerge) { 284 | executionData project.files().asFileTree // Start with an empty collection. 285 | destinationFile project.file("${project.buildDir}/jacoco/mergedReport.exec") 286 | 287 | doFirst { 288 | // Filter non existing files. 289 | def realExecutionData = project.files() 290 | 291 | executionData.each { 292 | if (it.exists()) { 293 | realExecutionData.setFrom(project.files(it) + realExecutionData.files) 294 | } 295 | } 296 | 297 | executionData = realExecutionData 298 | } 299 | } 300 | 301 | def mergedReportTask = project.task("jacocoTestReportMerged", type: JacocoReport, dependsOn: mergeTask) { 302 | executionData mergeTask.destinationFile 303 | 304 | reports { 305 | xml { 306 | enabled = extension.xml.enabled 307 | destination project.file("${project.buildDir}/reports/jacoco/jacoco.xml") 308 | } 309 | csv { 310 | enabled = extension.csv.enabled 311 | destination project.file("${project.buildDir}/reports/jacoco/jacoco.csv") 312 | } 313 | html { 314 | enabled = extension.html.enabled 315 | destination project.file("${project.buildDir}/reports/jacoco") 316 | } 317 | } 318 | 319 | // Start with empty collections. 320 | getClassDirectories().from(project.files()) 321 | getAdditionalSourceDirs().from(project.files()) 322 | getSourceDirectories().from(project.files()) 323 | } 324 | 325 | return [mergeTask, mergedReportTask] 326 | } 327 | 328 | static List getExcludes(final JunitJacocoExtension extension) { 329 | extension.excludes ?: [] 330 | } 331 | 332 | private static boolean isAndroidProject(final Project project) { 333 | final boolean isAndroidLibrary = project.plugins.hasPlugin('com.android.library') 334 | final boolean isAndroidApp = project.plugins.hasPlugin('com.android.application') 335 | final boolean isAndroidTest = project.plugins.hasPlugin('com.android.test') 336 | final boolean isAndroidDynamicFeature = project.plugins.hasPlugin('com.android.dynamic-feature') 337 | final boolean isAndroidInstantApp = project.plugins.hasPlugin('com.android.instantapp') 338 | return isAndroidLibrary || isAndroidApp || isAndroidTest || isAndroidDynamicFeature || isAndroidInstantApp 339 | } 340 | 341 | private static boolean isJavaProject(final Project project) { 342 | final boolean isJava = project.plugins.hasPlugin('java') 343 | final boolean isJavaLibrary = project.plugins.hasPlugin('java-library') 344 | final boolean isJavaGradlePlugin = project.plugins.hasPlugin('java-gradle-plugin') 345 | return isJava || isJavaLibrary || isJavaGradlePlugin 346 | } 347 | 348 | protected static boolean isKotlinAndroid(final Project project) { 349 | return project.plugins.hasPlugin('org.jetbrains.kotlin.android') 350 | } 351 | 352 | protected static boolean isKotlinMultiplatform(final Project project) { 353 | return project.plugins.hasPlugin('org.jetbrains.kotlin.multiplatform') 354 | } 355 | 356 | protected static boolean isAndroidApplication(final Project project) { 357 | return project.plugins.hasPlugin('com.android.application') 358 | } 359 | 360 | protected static boolean isAndroidLibrary(final Project project) { 361 | return project.plugins.hasPlugin('com.android.library') 362 | } 363 | 364 | protected static boolean isAndroidDynamicFeature(final Project project) { 365 | return project.plugins.hasPlugin('com.android.dynamic-feature') 366 | } 367 | 368 | private static boolean shouldIgnore(final Project project, final JunitJacocoExtension extension) { 369 | if (extension.ignoreProjects?.contains(project.name) || extension.ignoreProjects?.contains(project.path)) { 370 | // Regex could be slower. 371 | return true 372 | } 373 | 374 | if (extension.ignoreProjects != null) { 375 | for (String ignoredProject : extension.ignoreProjects) { 376 | if (project.name.find(ignoredProject) || project.path.find(ignoredProject)) { 377 | return true 378 | } 379 | } 380 | } 381 | 382 | return false 383 | } 384 | } 385 | -------------------------------------------------------------------------------- /src/main/groovy/com/vanniktech/android/junit/jacoco/JunitJacocoExtension.groovy: -------------------------------------------------------------------------------- 1 | package com.vanniktech.android.junit.jacoco 2 | 3 | /** 4 | * Extension for junit jacoco 5 | * @since 0.3.0 6 | */ 7 | class JunitJacocoExtension { 8 | /** 9 | * define the version of jacoco which should be used 10 | * @since 0.3.0 11 | */ 12 | String jacocoVersion = '0.8.7' 13 | 14 | /** 15 | * subprojects that should be ignored 16 | * @since 0.3.0 17 | */ 18 | List ignoreProjects = [] 19 | 20 | /** 21 | * Patterns of files that should be ignored 22 | * @since 0.5.0 23 | */ 24 | List excludes = [ 25 | '**/R.class', 26 | '**/R2.class', // ButterKnife Gradle Plugin. 27 | '**/R$*.class', 28 | '**/R2$*.class', // ButterKnife Gradle Plugin. 29 | '**/*$$*', 30 | '**/*$ViewInjector*.*', // Older ButterKnife Versions. 31 | '**/*$ViewBinder*.*', // Older ButterKnife Versions. 32 | '**/*_ViewBinding*.*', // Newer ButterKnife Versions. 33 | '**/BuildConfig.*', 34 | '**/Manifest*.*', 35 | '**/*$Lambda$*.*', // Jacoco can not handle several "$" in class name. 36 | '**/*Dagger*.*', // Dagger auto-generated code. 37 | '**/*MembersInjector*.*', // Dagger auto-generated code. 38 | '**/*_Provide*Factory*.*', // Dagger auto-generated code. 39 | '**/*_Factory*.*', // Dagger auto-generated code. 40 | '**/*$JsonObjectMapper.*', // LoganSquare auto-generated code. 41 | '**/*$inlined$*.*', // Kotlin specific, Jacoco can not handle several "$" in class name. 42 | '**/*$Icepick.*', // Icepick auto-generated code. 43 | '**/*$StateSaver.*', // android-state auto-generated code. 44 | '**/*AutoValue_*.*' // AutoValue auto-generated code. 45 | ] 46 | 47 | /** 48 | * Whether or not to include no location classes 49 | * @since 0.6.0 50 | */ 51 | boolean includeNoLocationClasses 52 | 53 | /** 54 | * Whether or not to include instrumentation coverage in the final global merged report. 55 | * Note that this will run all instrumentation tests when true. 56 | * @since 0.13.0 57 | */ 58 | boolean includeInstrumentationCoverageInMergedReport = false 59 | 60 | /** 61 | * Whether or not to generate an xml report 62 | * @since 0.17.0 63 | */ 64 | ReportConfig xml = new ReportConfig(true) 65 | 66 | /** 67 | * Whether or not to generate a csv report 68 | * @since 0.17.0 69 | */ 70 | ReportConfig csv = new ReportConfig(true) 71 | 72 | /** 73 | * Whether or not to generate a html report 74 | * @since 0.17.0 75 | */ 76 | ReportConfig html = new ReportConfig(true) 77 | } 78 | -------------------------------------------------------------------------------- /src/main/groovy/com/vanniktech/android/junit/jacoco/ReportConfig.groovy: -------------------------------------------------------------------------------- 1 | package com.vanniktech.android.junit.jacoco 2 | 3 | class ReportConfig { 4 | boolean enabled 5 | 6 | ReportConfig(boolean enabled) { 7 | this.enabled = enabled 8 | } 9 | } 10 | -------------------------------------------------------------------------------- /src/test/groovy/com/vanniktech/android/junit/jacoco/GenerationPluginSpec.groovy: -------------------------------------------------------------------------------- 1 | package com.vanniktech.android.junit.jacoco 2 | 3 | import org.gradle.testfixtures.ProjectBuilder 4 | import spock.lang.Specification 5 | import spock.lang.Unroll 6 | 7 | final class GenerationPluginSpec extends Specification { 8 | final static ANDROID_PLUGINS = ["com.android.application", "com.android.library", "com.android.test", "com.android.dynamic-feature"] 9 | final static COMPILE_SDK_VERSION = 28 10 | final static BUILD_TOOLS_VERSION = "28.0.3" 11 | final static APPLICATION_ID = "com.example" 12 | 13 | def project 14 | 15 | def "setup"() { 16 | project = ProjectBuilder.builder() 17 | .build() 18 | 19 | def manifest = new File(project.projectDir, 'src/main/AndroidManifest.xml') 20 | manifest.parentFile.mkdirs() 21 | manifest.write('') 22 | } 23 | 24 | @Unroll "#projectPlugin project"() { 25 | given: 26 | project.apply plugin: projectPlugin 27 | 28 | when: 29 | project.plugins.apply(GenerationPlugin) 30 | 31 | then: 32 | noExceptionThrown() 33 | 34 | where: 35 | projectPlugin << ANDROID_PLUGINS 36 | } 37 | 38 | def "android - all tasks created"() { 39 | given: 40 | project.apply plugin: "com.android.application" 41 | project.plugins.apply(GenerationPlugin) 42 | project.android { 43 | compileSdkVersion COMPILE_SDK_VERSION 44 | buildToolsVersion BUILD_TOOLS_VERSION 45 | 46 | defaultConfig { 47 | applicationId APPLICATION_ID 48 | } 49 | } 50 | 51 | when: 52 | project.evaluate() 53 | 54 | then: 55 | project.tasks.getByName("jacocoTestReportDebug") 56 | } 57 | 58 | def "android [buildTypes] - all tasks created"() { 59 | given: 60 | project.apply plugin: "com.android.application" 61 | project.plugins.apply(GenerationPlugin) 62 | project.android { 63 | compileSdkVersion COMPILE_SDK_VERSION 64 | buildToolsVersion BUILD_TOOLS_VERSION 65 | 66 | defaultConfig { 67 | applicationId APPLICATION_ID 68 | } 69 | 70 | buildTypes { 71 | debug {} 72 | release {} 73 | } 74 | } 75 | 76 | when: 77 | project.evaluate() 78 | 79 | then: 80 | project.tasks.getByName("jacocoTestReportDebug") 81 | project.tasks.getByName("jacocoTestReportRelease") 82 | } 83 | 84 | def "android [buildTypes + productFlavors] - all tasks created"() { 85 | given: 86 | project.apply plugin: "com.android.application" 87 | project.plugins.apply(GenerationPlugin) 88 | project.android { 89 | compileSdkVersion COMPILE_SDK_VERSION 90 | buildToolsVersion BUILD_TOOLS_VERSION 91 | 92 | defaultConfig { 93 | applicationId APPLICATION_ID 94 | } 95 | 96 | buildTypes { 97 | debug {} 98 | release {} 99 | } 100 | 101 | flavorDimensions "number" 102 | 103 | productFlavors { 104 | flavor1 { 105 | dimension "number" 106 | } 107 | flavor2 { 108 | dimension "number" 109 | } 110 | } 111 | } 112 | 113 | when: 114 | project.evaluate() 115 | 116 | then: 117 | project.tasks.getByName("jacocoTestReportFlavor1Debug") 118 | project.tasks.getByName("jacocoTestReportFlavor1Release") 119 | project.tasks.getByName("jacocoTestReportFlavor2Debug") 120 | project.tasks.getByName("jacocoTestReportFlavor2Release") 121 | } 122 | 123 | def "android [buildTypes + productFlavors + flavorDimensions] - all tasks created"() { 124 | given: 125 | project.apply plugin: "com.android.application" 126 | project.plugins.apply(GenerationPlugin) 127 | project.android { 128 | compileSdkVersion COMPILE_SDK_VERSION 129 | buildToolsVersion BUILD_TOOLS_VERSION 130 | 131 | defaultConfig { 132 | applicationId APPLICATION_ID 133 | } 134 | 135 | buildTypes { 136 | debug {} 137 | release {} 138 | } 139 | 140 | flavorDimensions "a", "b" 141 | 142 | productFlavors { 143 | flavor1 { dimension "a" } 144 | flavor2 { dimension "a" } 145 | flavor3 { dimension "b" } 146 | flavor4 { dimension "b" } 147 | } 148 | } 149 | 150 | when: 151 | project.evaluate() 152 | 153 | then: 154 | project.tasks.getByName("jacocoTestReportFlavor1Flavor3Debug") 155 | project.tasks.getByName("jacocoTestReportFlavor1Flavor3Release") 156 | project.tasks.getByName("jacocoTestReportFlavor2Flavor4Debug") 157 | project.tasks.getByName("jacocoTestReportFlavor2Flavor4Release") 158 | } 159 | } 160 | -------------------------------------------------------------------------------- /src/test/groovy/com/vanniktech/android/junit/jacoco/GenerationTest.groovy: -------------------------------------------------------------------------------- 1 | package com.vanniktech.android.junit.jacoco 2 | 3 | import org.gradle.api.Project 4 | import org.gradle.api.Task 5 | import org.gradle.testing.jacoco.plugins.JacocoPlugin 6 | import org.gradle.testing.jacoco.tasks.JacocoReport 7 | import org.junit.Test 8 | 9 | import java.nio.file.Paths 10 | 11 | import static com.vanniktech.android.junit.jacoco.ProjectHelper.ProjectType.* 12 | 13 | class GenerationTest { 14 | def LANGUAGES = ["clojure", "groovy", "java", "kotlin", "scala"] 15 | 16 | @Test void addJacocoAndroidAppWithFlavors() { 17 | def androidAppProject = ProjectHelper.prepare(ANDROID_APPLICATION).withRedBlueFlavors().get() 18 | 19 | GenerationPlugin.addJacoco(androidAppProject, new JunitJacocoExtension()) 20 | 21 | assertJacocoAndroidWithFlavors(androidAppProject) 22 | } 23 | 24 | @Test void addJacocoAndroidLibraryWithFlavors() { 25 | def androidLibraryProject = ProjectHelper.prepare(ANDROID_LIBRARY).withRedBlueFlavors().get() 26 | 27 | GenerationPlugin.addJacoco(androidLibraryProject, new JunitJacocoExtension()) 28 | 29 | assertJacocoAndroidWithFlavors(androidLibraryProject) 30 | } 31 | 32 | @Test void addJacocoAndroidApp() { 33 | def androidAppProject = ProjectHelper.prepare(ANDROID_APPLICATION).get() 34 | 35 | GenerationPlugin.addJacoco(androidAppProject, new JunitJacocoExtension()) 36 | 37 | assertJacocoAndroidWithoutFlavors(androidAppProject, true) 38 | } 39 | 40 | @Test void addJacocoAndroidLibrary() { 41 | def androidLibraryProject = ProjectHelper.prepare(ANDROID_LIBRARY).get() 42 | 43 | GenerationPlugin.addJacoco(androidLibraryProject, new JunitJacocoExtension()) 44 | 45 | assertJacocoAndroidWithoutFlavors(androidLibraryProject, true) 46 | } 47 | 48 | @Test void addJacocoAndroidDynamicFeature() { 49 | def androidLibraryProject = ProjectHelper.prepare(ANDROID_DYNAMIC_FEATURE).get() 50 | 51 | GenerationPlugin.addJacoco(androidLibraryProject, new JunitJacocoExtension()) 52 | 53 | assertJacocoAndroidWithoutFlavors(androidLibraryProject, true) 54 | } 55 | 56 | @Test void addJacocoAndroidAppWithoutInstrumentationCoverage() { 57 | def androidAppProject = ProjectHelper.prepare(ANDROID_APPLICATION).get() 58 | androidAppProject.android.buildTypes.each { it.testCoverageEnabled = false } 59 | 60 | GenerationPlugin.addJacoco(androidAppProject, new JunitJacocoExtension()) 61 | 62 | assertJacocoAndroidWithoutFlavors(androidAppProject, false) 63 | } 64 | 65 | @Test void addJacocoAndroidLibraryWithoutInstrumentationCoverage() { 66 | def androidLibraryProject = ProjectHelper.prepare(ANDROID_LIBRARY).get() 67 | androidLibraryProject.android.buildTypes.each { it.testCoverageEnabled = false } 68 | 69 | GenerationPlugin.addJacoco(androidLibraryProject, new JunitJacocoExtension()) 70 | 71 | assertJacocoAndroidWithoutFlavors(androidLibraryProject, false) 72 | } 73 | 74 | @Test void addJacocoAndroidDynamicFeatureWithoutInstrumentationCoverage() { 75 | def androidLibraryProject = ProjectHelper.prepare(ANDROID_DYNAMIC_FEATURE).get() 76 | androidLibraryProject.android.buildTypes.each { it.testCoverageEnabled = false } 77 | 78 | GenerationPlugin.addJacoco(androidLibraryProject, new JunitJacocoExtension()) 79 | 80 | assertJacocoAndroidWithoutFlavors(androidLibraryProject, false) 81 | } 82 | 83 | @Test void addJacocoAndroidTest() { 84 | def androidTestProject = ProjectHelper.prepare(ANDROID_TEST).get() 85 | assert !GenerationPlugin.addJacoco(androidTestProject, new JunitJacocoExtension()) 86 | } 87 | 88 | @Test void addJacocoJava() { 89 | def javaProject = ProjectHelper.prepare(JAVA).get() 90 | 91 | GenerationPlugin.addJacoco(javaProject, new JunitJacocoExtension()) 92 | 93 | assertJacocoJava(javaProject) 94 | } 95 | 96 | @Test void jacocoVersion() { 97 | final def extension = new JunitJacocoExtension() 98 | extension.jacocoVersion = '0.7.6.201602180812' 99 | def androidAppProject = ProjectHelper.prepare(ANDROID_APPLICATION).get() 100 | def androidLibraryProject = ProjectHelper.prepare(ANDROID_LIBRARY).get() 101 | def javaProject = ProjectHelper.prepare(JAVA).get() 102 | 103 | GenerationPlugin.addJacoco(androidAppProject, extension) 104 | GenerationPlugin.addJacoco(androidLibraryProject, extension) 105 | GenerationPlugin.addJacoco(javaProject, extension) 106 | 107 | assert androidAppProject.jacoco.toolVersion == extension.jacocoVersion 108 | assert androidAppProject.android.jacoco.version == extension.jacocoVersion 109 | assert androidLibraryProject.jacoco.toolVersion == extension.jacocoVersion 110 | assert androidLibraryProject.android.jacoco.version == extension.jacocoVersion 111 | assert javaProject.jacoco.toolVersion == extension.jacocoVersion 112 | } 113 | 114 | @Test void ignoreProjects() { 115 | final def extension = new JunitJacocoExtension() 116 | final def projects = [ 117 | ProjectHelper.prepare(ANDROID_APPLICATION).get(), 118 | ProjectHelper.prepare(ANDROID_LIBRARY).get(), 119 | ProjectHelper.prepare(JAVA).get()] as Project[] 120 | 121 | for (final def project : projects) { 122 | extension.ignoreProjects = [project.name] 123 | 124 | assert !GenerationPlugin.addJacoco(project, extension) 125 | assert !project.plugins.hasPlugin(JacocoPlugin) 126 | } 127 | } 128 | 129 | @Test void ignoreProjectsPath() { 130 | final def extension = new JunitJacocoExtension() 131 | final def projects = [ 132 | ProjectHelper.prepare(ANDROID_APPLICATION).get(), 133 | ProjectHelper.prepare(ANDROID_LIBRARY).get(), 134 | ProjectHelper.prepare(JAVA).get()] as Project[] 135 | 136 | for (final def project : projects) { 137 | extension.ignoreProjects = [project.path] 138 | 139 | assert !GenerationPlugin.addJacoco(project, extension) 140 | assert !project.plugins.hasPlugin(JacocoPlugin) 141 | } 142 | } 143 | 144 | @Test void ignoreProjectsRegexPath() { 145 | final def extension = new JunitJacocoExtension() 146 | final def projects = [ 147 | ProjectHelper.prepare(ANDROID_APPLICATION).get(), 148 | ProjectHelper.prepare(ANDROID_LIBRARY).get(), 149 | ProjectHelper.prepare(JAVA).get()] as Project[] 150 | 151 | for (final def project : projects) { 152 | extension.ignoreProjects = [".*"] 153 | 154 | assert !GenerationPlugin.addJacoco(project, extension) 155 | assert !project.plugins.hasPlugin(JacocoPlugin) 156 | } 157 | } 158 | 159 | @Test void ignoreProjectsRegexName() { 160 | final def extension = new JunitJacocoExtension() 161 | final def projects = [ 162 | ProjectHelper.prepare(ANDROID_APPLICATION).get(), 163 | ProjectHelper.prepare(ANDROID_LIBRARY).get()] as Project[] 164 | 165 | for (final def project : projects) { 166 | extension.ignoreProjects = ["android*"] 167 | 168 | assert !GenerationPlugin.addJacoco(project, extension) 169 | assert !project.plugins.hasPlugin(JacocoPlugin) 170 | } 171 | } 172 | 173 | @Test void ignoreProjectsWrongRegexName() { 174 | final def extension = new JunitJacocoExtension() 175 | final def projects = [ 176 | ProjectHelper.prepare(ANDROID_APPLICATION).get(), 177 | ProjectHelper.prepare(ANDROID_LIBRARY).get()] as Project[] 178 | 179 | for (final def project : projects) { 180 | extension.ignoreProjects = ["androidFFF*"] 181 | 182 | assert GenerationPlugin.addJacoco(project, extension) 183 | assert project.plugins.hasPlugin(JacocoPlugin) 184 | } 185 | } 186 | 187 | @Test void androidAppBuildExecutesJacocoTask() { 188 | def androidAppProject = ProjectHelper.prepare(ANDROID_APPLICATION).get() 189 | 190 | GenerationPlugin.addJacoco(androidAppProject, new JunitJacocoExtension()) 191 | 192 | assert taskDependsOn(androidAppProject.check, 'jacocoTestReportDebug') 193 | assert taskDependsOn(androidAppProject.check, 'jacocoTestReportRelease') 194 | } 195 | 196 | @Test void androidLibraryBuildExecutesJacocoTask() { 197 | def androidLibraryProject = ProjectHelper.prepare(ANDROID_LIBRARY).get() 198 | 199 | GenerationPlugin.addJacoco(androidLibraryProject, new JunitJacocoExtension()) 200 | 201 | assert taskDependsOn(androidLibraryProject.check, 'jacocoTestReportDebug') 202 | assert taskDependsOn(androidLibraryProject.check, 'jacocoTestReportRelease') 203 | } 204 | 205 | @Test void javaBuildExecutesJacocoTask() { 206 | def javaProject = ProjectHelper.prepare(JAVA).get() 207 | 208 | GenerationPlugin.addJacoco(javaProject, new JunitJacocoExtension()) 209 | 210 | assert taskDependsOn(javaProject.check, 'jacocoTestReport') 211 | } 212 | 213 | @Test void mergedJacocoReportDoesNotHaveDependencies() { 214 | def rootProject = ProjectHelper.prepare(ROOT).get() 215 | 216 | def mergeJacocoReports = rootProject.tasks.findByName("mergeJacocoReports") 217 | def jacocoTestReportMerged = rootProject.tasks.findByName("jacocoTestReportMerged") 218 | 219 | assert mergeJacocoReports != null 220 | assert jacocoTestReportMerged != null 221 | 222 | values().findAll { it != ROOT && it != ANDROID_TEST }.each { 223 | def project = ProjectHelper.prepare(it, rootProject).get() 224 | GenerationPlugin.addJacoco(project, new JunitJacocoExtension(), mergeJacocoReports, jacocoTestReportMerged) 225 | if (it == JAVA) { 226 | assertJacocoJava(project) 227 | } else { 228 | assertJacocoAndroidWithoutFlavors(project, true) 229 | } 230 | } 231 | 232 | assert mergeJacocoReports.dependsOn.isEmpty() 233 | assert jacocoTestReportMerged.dependsOn.size() == 1 234 | assert jacocoTestReportMerged.dependsOn.contains(mergeJacocoReports) 235 | } 236 | 237 | private void assertJacocoAndroidWithFlavors(final Project project) { 238 | assert project.plugins.hasPlugin(JacocoPlugin) 239 | 240 | assert project.jacoco.toolVersion == '0.8.7' 241 | 242 | assertTask(project, 'red', 'debug') 243 | assertTask(project, 'red', 'release') 244 | assertTask(project, 'blue', 'debug') 245 | assertTask(project, 'blue', 'release') 246 | } 247 | 248 | private void assertTask(final Project project, final String flavor, final String buildType) { 249 | final def task = project.tasks.findByName("jacocoTestReport${flavor.capitalize()}${buildType.capitalize()}") 250 | 251 | assert task instanceof JacocoReport 252 | 253 | task.with { 254 | assert description == "Generate Jacoco coverage reports after running ${flavor}${buildType.capitalize()} tests." 255 | assert group == 'Reporting' 256 | 257 | assert executionData.singleFile == project.file("${project.buildDir}/jacoco/test${flavor.capitalize()}${buildType.capitalize()}UnitTest.exec") 258 | 259 | assert additionalSourceDirs.size() == 15 260 | LANGUAGES.every { 261 | assert additionalSourceDirs.contains(project.file("src/main/$it")) 262 | assert additionalSourceDirs.contains(project.file("src/${buildType}/$it")) 263 | assert additionalSourceDirs.contains(project.file("src/${flavor}/$it")) 264 | } 265 | 266 | assert sourceDirectories.size() == 15 267 | LANGUAGES.every { 268 | assert sourceDirectories.contains(project.file("src/main/$it")) 269 | assert sourceDirectories.contains(project.file("src/${buildType}/$it")) 270 | assert sourceDirectories.contains(project.file("src/${flavor}/$it")) 271 | } 272 | 273 | assert reports.xml.enabled 274 | assert reports.xml.destination.toPath() == Paths.get(project.buildDir.absolutePath, "/reports/jacoco/${flavor}${buildType.capitalize()}/jacoco.xml") 275 | assert reports.csv.enabled 276 | assert reports.csv.destination.toPath() == Paths.get(project.buildDir.absolutePath, "/reports/jacoco/${flavor}${buildType.capitalize()}/jacoco.csv") 277 | assert reports.html.enabled 278 | assert reports.html.destination.toPath() == Paths.get(project.buildDir.absolutePath, "/reports/jacoco/${flavor}${buildType.capitalize()}") 279 | 280 | assert classDirectories.getFrom().first().dir == project.file("build/") 281 | 282 | assert contentEquals(classDirectories.getFrom().first().includes, [ 283 | "**/intermediates/classes/${flavor}/${buildType}/**".toString(), 284 | "**/intermediates/javac/${flavor}${buildType.capitalize()}/*/classes/**".toString(), 285 | "**/intermediates/javac/${flavor}${buildType.capitalize()}/classes/**".toString() 286 | ]) 287 | 288 | if (hasKotlin(project)) { 289 | assert contentEquals(classDirectories.getFrom().first().includes, [ 290 | "**/intermediates/classes/${flavor}/${buildType}/**", 291 | "**/intermediates/javac/${flavor}${buildType.capitalize()}/*/classes/**", 292 | "**/intermediates/javac/${flavor}${buildType.capitalize()}/classes/**", 293 | "**/tmp/kotlin-classes/${buildType}/**", 294 | "**/tmp/kotlin-classes/${flavor}${buildType.capitalize()}/**"]) 295 | } else { 296 | assert contentEquals(classDirectories.getFrom().first().includes, [ 297 | "**/intermediates/classes/${flavor}/${buildType}/**".toString(), 298 | "**/intermediates/javac/${flavor}${buildType.capitalize()}/*/classes/**".toString(), 299 | "**/intermediates/javac/${flavor}${buildType.capitalize()}/classes/**".toString() 300 | ]) 301 | } 302 | 303 | assert taskDependsOn(task, "test${flavor.capitalize()}${buildType.capitalize()}UnitTest") 304 | assert taskDependsOn(project.tasks.findByName('check'), "jacocoTestReport${flavor.capitalize()}${buildType.capitalize()}") 305 | } 306 | } 307 | 308 | private void assertJacocoAndroidWithoutFlavors(final Project project, final boolean hasCoverage) { 309 | assert project.plugins.hasPlugin(JacocoPlugin) 310 | 311 | assert project.jacoco.toolVersion == '0.8.7' 312 | 313 | final def debugTask = project.tasks.findByName('jacocoTestReportDebug') 314 | 315 | assert debugTask instanceof JacocoReport 316 | 317 | debugTask.with { 318 | assert description == 'Generate Jacoco coverage reports after running debug tests.' 319 | assert group == 'Reporting' 320 | 321 | assert executionData.singleFile == project.file("${project.buildDir}/jacoco/testDebugUnitTest.exec") 322 | 323 | assert additionalSourceDirs.size() == 10 324 | LANGUAGES.every { 325 | assert additionalSourceDirs.contains(project.file("src/main/$it")) 326 | assert additionalSourceDirs.contains(project.file("src/debug/$it")) 327 | } 328 | 329 | assert sourceDirectories.size() == 10 330 | LANGUAGES.every { 331 | assert sourceDirectories.contains(project.file("src/main/$it")) 332 | assert sourceDirectories.contains(project.file("src/debug/$it")) 333 | } 334 | 335 | assert reports.xml.enabled 336 | assert reports.xml.destination.toPath() == Paths.get(project.buildDir.absolutePath, "/reports/jacoco/debug/jacoco.xml") 337 | assert reports.csv.enabled 338 | assert reports.csv.destination.toPath() == Paths.get(project.buildDir.absolutePath, "/reports/jacoco/debug/jacoco.csv") 339 | assert reports.html.enabled 340 | assert reports.html.destination.toPath() == Paths.get(project.buildDir.absolutePath, "/reports/jacoco/debug") 341 | 342 | assert classDirectories.getFrom().first().dir == project.file("build/") 343 | if (hasKotlin(project)) { 344 | assert contentEquals(classDirectories.getFrom().first().includes, [ 345 | '**/intermediates/classes/debug/**', 346 | '**/intermediates/javac/debug/*/classes/**', 347 | "**/intermediates/javac/debug/classes/**", 348 | '**/tmp/kotlin-classes/debug/**' 349 | ]) 350 | } else { 351 | assert contentEquals(classDirectories.getFrom().first().includes, [ 352 | '**/intermediates/classes/debug/**', 353 | '**/intermediates/javac/debug/*/classes/**', 354 | "**/intermediates/javac/debug/classes/**" 355 | ]) 356 | } 357 | 358 | assert taskDependsOn(debugTask, 'testDebugUnitTest') 359 | assert taskDependsOn(project.tasks.findByName('check'), 'jacocoTestReportDebug') 360 | } 361 | 362 | final def debugTaskCombined = project.tasks.findByName('combinedTestReportDebug') 363 | if (hasCoverage) { 364 | assert debugTaskCombined instanceof JacocoReport 365 | 366 | debugTaskCombined.with { 367 | assert description == 'Generate Jacoco coverage reports after running debug tests.' 368 | assert group == 'Reporting' 369 | 370 | assert executionData.singleFile == project.file("${project.buildDir}/jacoco/testDebugUnitTest.exec") 371 | 372 | assert additionalSourceDirs.size() == 10 373 | LANGUAGES.every { 374 | assert additionalSourceDirs.contains(project.file("src/main/$it")) 375 | assert additionalSourceDirs.contains(project.file("src/debug/$it")) 376 | } 377 | 378 | assert sourceDirectories.size() == 10 379 | LANGUAGES.every { 380 | assert sourceDirectories.contains(project.file("src/main/$it")) 381 | assert sourceDirectories.contains(project.file("src/debug/$it")) 382 | } 383 | 384 | assert reports.xml.enabled 385 | assert reports.xml.destination.toPath() == Paths.get(project.buildDir.absolutePath, '/reports/jacocoCombined/debug/jacoco.xml') 386 | assert reports.csv.enabled 387 | assert reports.csv.destination.toPath() == Paths.get(project.buildDir.absolutePath, '/reports/jacocoCombined/debug/jacoco.csv') 388 | assert reports.html.enabled 389 | assert reports.html.destination.toPath() == Paths.get(project.buildDir.absolutePath, '/reports/jacocoCombined/debug') 390 | 391 | assert classDirectories.getFrom().first().dir == project.file("build/") 392 | if (hasKotlin(project)) { 393 | assert contentEquals(classDirectories.getFrom().first().includes, [ 394 | '**/intermediates/classes/debug/**', 395 | '**/intermediates/javac/debug/*/classes/**', 396 | "**/intermediates/javac/debug/classes/**", 397 | '**/tmp/kotlin-classes/debug/**' 398 | ]) 399 | } else { 400 | assert contentEquals(classDirectories.getFrom().first().includes, [ 401 | '**/intermediates/classes/debug/**', 402 | '**/intermediates/javac/debug/*/classes/**', 403 | "**/intermediates/javac/debug/classes/**", 404 | ]) 405 | } 406 | 407 | assert taskDependsOn(debugTaskCombined, 'testDebugUnitTest') 408 | assert taskDependsOn(debugTaskCombined, 'createDebugCoverageReport') 409 | assert taskDependsOn(project.tasks.findByName('check'), 'combinedTestReportDebug') 410 | } 411 | } else { 412 | assert debugTaskCombined == null 413 | } 414 | 415 | final def releaseTask = project.tasks.findByName('jacocoTestReportRelease') 416 | 417 | assert releaseTask instanceof JacocoReport 418 | 419 | releaseTask.with { 420 | assert description == 'Generate Jacoco coverage reports after running release tests.' 421 | assert group == 'Reporting' 422 | 423 | assert executionData.singleFile == project.file("${project.buildDir}/jacoco/testReleaseUnitTest.exec") 424 | 425 | assert additionalSourceDirs.size() == 10 426 | LANGUAGES.every { 427 | assert additionalSourceDirs.contains(project.file("src/main/$it")) 428 | assert additionalSourceDirs.contains(project.file("src/release/$it")) 429 | } 430 | 431 | assert sourceDirectories.size() == 10 432 | LANGUAGES.every { 433 | assert sourceDirectories.contains(project.file("src/main/$it")) 434 | assert sourceDirectories.contains(project.file("src/release/$it")) 435 | } 436 | 437 | assert reports.xml.enabled 438 | assert reports.xml.destination.toPath() == Paths.get(project.buildDir.absolutePath, '/reports/jacoco/release/jacoco.xml') 439 | assert reports.csv.enabled 440 | assert reports.csv.destination.toPath() == Paths.get(project.buildDir.absolutePath, '/reports/jacoco/release/jacoco.csv') 441 | assert reports.html.enabled 442 | assert reports.html.destination.toPath() == Paths.get(project.buildDir.absolutePath, '/reports/jacoco/release') 443 | 444 | assert classDirectories.getFrom().first().dir == project.file("build/") 445 | if (hasKotlin(project)) { 446 | assert contentEquals(classDirectories.getFrom().first().includes, [ 447 | '**/intermediates/classes/release/**', 448 | '**/intermediates/javac/release/*/classes/**', 449 | "**/intermediates/javac/release/classes/**", 450 | '**/tmp/kotlin-classes/release/**' 451 | ]) 452 | } else { 453 | assert contentEquals(classDirectories.getFrom().first().includes, [ 454 | '**/intermediates/classes/release/**', 455 | '**/intermediates/javac/release/*/classes/**', 456 | "**/intermediates/javac/release/classes/**" 457 | ]) 458 | } 459 | 460 | assert taskDependsOn(releaseTask, 'testReleaseUnitTest') 461 | assert taskDependsOn(project.tasks.findByName('check'), 'jacocoTestReportRelease') 462 | } 463 | 464 | final def releaseTaskCombined = project.tasks.findByName('combinedTestReportRelease') 465 | 466 | if (hasCoverage) { 467 | assert releaseTaskCombined instanceof JacocoReport 468 | 469 | releaseTaskCombined.with { 470 | assert description == 'Generate Jacoco coverage reports after running release tests.' 471 | assert group == 'Reporting' 472 | 473 | assert executionData.singleFile == project.file("${project.buildDir}/jacoco/testReleaseUnitTest.exec") 474 | 475 | assert additionalSourceDirs.size() == 10 476 | LANGUAGES.every { 477 | assert additionalSourceDirs.contains(project.file("src/main/$it")) 478 | assert additionalSourceDirs.contains(project.file("src/release/$it")) 479 | } 480 | 481 | assert sourceDirectories.size() == 10 482 | LANGUAGES.every { 483 | assert sourceDirectories.contains(project.file("src/main/$it")) 484 | assert sourceDirectories.contains(project.file("src/release/$it")) 485 | } 486 | 487 | assert reports.xml.enabled 488 | assert reports.xml.destination.toPath() == Paths.get(project.buildDir.absolutePath, '/reports/jacocoCombined/release/jacoco.xml') 489 | assert reports.csv.enabled 490 | assert reports.csv.destination.toPath() == Paths.get(project.buildDir.absolutePath, '/reports/jacocoCombined/release/jacoco.csv') 491 | assert reports.html.enabled 492 | assert reports.html.destination.toPath() == Paths.get(project.buildDir.absolutePath, '/reports/jacocoCombined/release') 493 | 494 | assert classDirectories.getFrom().first().dir == project.file("build/") 495 | if (hasKotlin(project)) { 496 | assert contentEquals(classDirectories.getFrom().first().includes, [ 497 | '**/intermediates/classes/release/**', 498 | '**/intermediates/javac/release/*/classes/**', 499 | "**/intermediates/javac/release/classes/**", 500 | '**/tmp/kotlin-classes/release/**' 501 | ]) 502 | } else { 503 | assert contentEquals(classDirectories.getFrom().first().includes, [ 504 | '**/intermediates/classes/release/**', 505 | '**/intermediates/javac/release/*/classes/**', 506 | "**/intermediates/javac/release/classes/**", 507 | ]) 508 | } 509 | 510 | assert taskDependsOn(releaseTaskCombined, 'testReleaseUnitTest') 511 | assert taskDependsOn(releaseTaskCombined, 'createReleaseCoverageReport') 512 | assert taskDependsOn(project.tasks.findByName('check'), 'combinedTestReportRelease') 513 | } 514 | } else { 515 | assert releaseTaskCombined == null 516 | } 517 | } 518 | 519 | private void assertJacocoJava(final Project project) { 520 | assert project.plugins.hasPlugin(JacocoPlugin) 521 | 522 | assert project.jacoco.toolVersion == '0.8.7' 523 | 524 | final def task = project.tasks.findByName('jacocoTestReport') 525 | 526 | assert task instanceof JacocoReport 527 | 528 | task.with { 529 | assert description == 'Generate Jacoco coverage reports.' 530 | assert group == 'Reporting' 531 | 532 | assert executionData.singleFile == project.file("${project.buildDir}/jacoco/test.exec") 533 | 534 | assert additionalSourceDirs.size() == 5 535 | LANGUAGES.every { 536 | assert additionalSourceDirs.contains(project.file("src/main/$it")) 537 | } 538 | 539 | assert sourceDirectories.size() == 5 540 | LANGUAGES.every { 541 | assert sourceDirectories.contains(project.file("src/main/$it")) 542 | } 543 | 544 | assert classDirectories.size() == 2 // First one is empty and the second fileTree is the one we plant. 545 | assert classDirectories.getFrom()[1].dir == project.file("build/") 546 | assert contentEquals(classDirectories.getFrom()[1].includes, ['**/classes/**/main/**']) 547 | 548 | assert reports.xml.enabled 549 | assert reports.csv.enabled 550 | assert reports.html.enabled 551 | 552 | assert taskDependsOn(task, 'test') 553 | } 554 | } 555 | 556 | static boolean contentEquals(Collection c1, Collection c2) { 557 | return c1.containsAll(c2) && c2.containsAll(c1) 558 | } 559 | 560 | static boolean taskDependsOn(final Task task, final String taskName) { 561 | final def it = task.dependsOn.iterator() 562 | 563 | while (it.hasNext()) { 564 | final def item = it.next() 565 | 566 | if (item.toString() == taskName) { 567 | return true 568 | } 569 | } 570 | 571 | return false 572 | } 573 | 574 | static boolean hasKotlin(Project project) { 575 | return project.plugins.hasPlugin('org.jetbrains.kotlin.android') || project.plugins.hasPlugin('org.jetbrains.kotlin.multiplatform') 576 | } 577 | 578 | @Test void getExcludesDefault() { 579 | final def excludes = GenerationPlugin.getExcludes(new JunitJacocoExtension()) 580 | 581 | assert excludes.size == 20 582 | assert excludes.contains('**/R.class') 583 | assert excludes.contains('**/R2.class') 584 | assert excludes.contains('**/R$*.class') 585 | assert excludes.contains('**/R2$*.class') 586 | assert excludes.contains('**/*$$*') 587 | assert excludes.contains('**/*$ViewInjector*.*') 588 | assert excludes.contains('**/*$ViewBinder*.*') 589 | assert excludes.contains('**/*_ViewBinding*.*') 590 | assert excludes.contains('**/BuildConfig.*') 591 | assert excludes.contains('**/Manifest*.*') 592 | assert excludes.contains('**/*$Lambda$*.*') 593 | assert excludes.contains('**/*Dagger*.*') 594 | assert excludes.contains('**/*MembersInjector*.*') 595 | assert excludes.contains('**/*_Provide*Factory*.*') 596 | assert excludes.contains('**/*_Factory*.*') 597 | assert excludes.contains('**/*$JsonObjectMapper.*') 598 | assert excludes.contains('**/*$inlined$*.*') 599 | assert excludes.contains('**/*$Icepick.*') 600 | assert excludes.contains('**/*$StateSaver.*') 601 | assert excludes.contains('**/*AutoValue_*.*') 602 | } 603 | 604 | @Test void getExcludesCustom() { 605 | final def extension = new JunitJacocoExtension() 606 | extension.excludes = new ArrayList<>() 607 | extension.excludes.add("**/*.java") 608 | 609 | final def excludes = GenerationPlugin.getExcludes(extension) 610 | 611 | assert excludes == extension.excludes 612 | } 613 | 614 | @Test void getExcludesCustomPlus() { 615 | final def extension = new JunitJacocoExtension() 616 | extension.excludes.add("**/*custom*.java") 617 | 618 | final def excludes = GenerationPlugin.getExcludes(extension) 619 | 620 | assert excludes == extension.excludes 621 | assert 1 < excludes.size() // Includes defaults 622 | } 623 | 624 | @Test void getExcludesNull() { 625 | final def extension = new JunitJacocoExtension() 626 | extension.excludes = null 627 | 628 | final def excludes = GenerationPlugin.getExcludes(extension) 629 | 630 | assert null != excludes 631 | assert 0 == excludes.size() 632 | } 633 | } 634 | -------------------------------------------------------------------------------- /src/test/groovy/com/vanniktech/android/junit/jacoco/JunitJacocoExtensionTest.groovy: -------------------------------------------------------------------------------- 1 | package com.vanniktech.android.junit.jacoco 2 | 3 | import org.junit.Test 4 | 5 | class JunitJacocoExtensionTest { 6 | @Test void defaults() { 7 | def extension = new JunitJacocoExtension() 8 | 9 | assert extension.jacocoVersion == '0.8.7' 10 | assert extension.ignoreProjects.size() == 0 11 | assert extension.excludes != null 12 | assert !extension.includeNoLocationClasses 13 | assert !extension.includeInstrumentationCoverageInMergedReport 14 | assert extension.xml.enabled 15 | assert extension.csv.enabled 16 | assert extension.html.enabled 17 | } 18 | } 19 | -------------------------------------------------------------------------------- /src/test/groovy/com/vanniktech/android/junit/jacoco/ProjectHelper.groovy: -------------------------------------------------------------------------------- 1 | package com.vanniktech.android.junit.jacoco 2 | 3 | import com.android.build.gradle.AppExtension 4 | import com.android.build.gradle.LibraryExtension 5 | import com.android.build.gradle.TestExtension 6 | import com.android.build.gradle.api.BaseVariant 7 | import com.android.build.gradle.internal.coverage.JacocoOptions 8 | import com.android.builder.model.BuildType 9 | import groovy.mock.interceptor.MockFor 10 | import org.gradle.api.Project 11 | import org.gradle.testfixtures.ProjectBuilder 12 | 13 | /** Provides projects for testing */ 14 | final class ProjectHelper { 15 | static ProjectHelper prepare(ProjectType projectType) { 16 | return prepare(projectType, null) 17 | } 18 | 19 | static ProjectHelper prepare(ProjectType projectType, Project parent) { 20 | return new ProjectHelper(projectType, parent) 21 | } 22 | 23 | private final ProjectType projectType 24 | private final Project project 25 | 26 | private ProjectHelper(ProjectType projectType, Project parent) { 27 | this.projectType = projectType 28 | 29 | def builder = ProjectBuilder.builder().withParent(parent) 30 | 31 | switch (projectType) { 32 | case ProjectType.ROOT: 33 | project = builder.withName('root').build() 34 | project.extensions.create('junitJacoco', JunitJacocoExtension) 35 | GenerationPlugin.addJacocoMergeToRootProject(project, project.junitJacoco) 36 | break 37 | case ProjectType.JAVA: 38 | project = builder.withName('java').build() 39 | break 40 | case ProjectType.ANDROID_APPLICATION: 41 | case ProjectType.ANDROID_KOTLIN_APPLICATION: 42 | case ProjectType.ANDROID_DYNAMIC_FEATURE: 43 | project = builder.withName('android app').build() 44 | def androidMock = new MockFor(AppExtension) 45 | def buildTypesMock = ["debug", "release"].collect { bt -> 46 | def type = new MockFor(BuildType) 47 | type.metaClass.getName = { bt } 48 | type.metaClass.testCoverageEnabled = true 49 | type 50 | } 51 | androidMock.metaClass.getBuildTypes = { buildTypesMock } 52 | def appVariants = buildTypesMock.collect { bt -> 53 | def variant = new MockFor(BaseVariant) 54 | variant.metaClass.getFlavorName = { null } 55 | variant.metaClass.getBuildType = { bt } 56 | variant 57 | } 58 | androidMock.metaClass.getApplicationVariants = { appVariants } 59 | androidMock.metaClass.testOptions = null 60 | androidMock.metaClass.jacoco = mockJacocoOptions() 61 | project.metaClass.android = androidMock 62 | // mock .all{ } function from android gradle lib with standard groovy .each{ } 63 | project.android.applicationVariants.metaClass.all = { delegate.each(it) } 64 | break 65 | case ProjectType.ANDROID_LIBRARY: 66 | case ProjectType.ANDROID_KOTLIN_MULTIPLATFORM: 67 | project = builder.withName('android library').build() 68 | def androidMock = new MockFor(LibraryExtension) 69 | def buildTypesMock = ["debug", "release"].collect { bt -> 70 | def type = new MockFor(BuildType) 71 | type.metaClass.getName = { bt } 72 | type.metaClass.testCoverageEnabled = true 73 | type 74 | } 75 | androidMock.metaClass.getBuildTypes = { buildTypesMock } 76 | def appVariants = buildTypesMock.collect { bt -> 77 | def variant = new MockFor(BaseVariant) 78 | variant.metaClass.getFlavorName = { null } 79 | variant.metaClass.getBuildType = { bt } 80 | variant 81 | } 82 | androidMock.metaClass.getLibraryVariants = { appVariants } 83 | androidMock.metaClass.testOptions = null 84 | androidMock.metaClass.jacoco = mockJacocoOptions() 85 | project.metaClass.android = androidMock 86 | // mock .all{ } function from android gradle lib with standard groovy .each{ } 87 | project.android.libraryVariants.metaClass.all = { delegate.each(it) } 88 | break 89 | case ProjectType.ANDROID_TEST: 90 | project = builder.withName('android test').build() 91 | def androidMock = new MockFor(TestExtension) 92 | androidMock.metaClass.testOptions = null 93 | androidMock.metaClass.jacoco = mockJacocoOptions() 94 | project.metaClass.android = androidMock 95 | break 96 | } 97 | 98 | if (projectType.pluginNames != null) { 99 | for (String pluginName : projectType.pluginNames) { 100 | if (pluginName) { 101 | project.plugins.apply(pluginName) 102 | } 103 | } 104 | } 105 | } 106 | 107 | private static def mockJacocoOptions(){ 108 | def options = new MockFor(JacocoOptions) 109 | options.metaClass.version = '7.9.0' 110 | return options 111 | } 112 | 113 | /** Adds flavors to project, only for Android based projects */ 114 | ProjectHelper withRedBlueFlavors() { 115 | if (projectType == ProjectType.JAVA || projectType == ProjectType.ROOT) { 116 | throw new UnsupportedOperationException('Not supported with Java or plain projects') 117 | } 118 | 119 | def customFlavors = [ 120 | red : [applicationId: 'com.example.red'], 121 | blue: [applicationId: 'com.example.blue'] 122 | ] 123 | 124 | def variants = customFlavors.collect { flavorName, config -> 125 | project.android.buildTypes.collect { buildType -> 126 | def variant = new MockFor(BaseVariant) 127 | variant.metaClass.getBuildType = { 128 | def type = new MockFor(BuildType) 129 | type.metaClass.getName = { buildType.name } 130 | type.metaClass.testCoverageEnabled = true 131 | type 132 | } 133 | variant.metaClass.getFlavorName = { flavorName } 134 | variant.metaClass.getApplicationId = { config.applicationId } 135 | variant 136 | } 137 | }.flatten() 138 | 139 | switch (projectType) { 140 | case ProjectType.ANDROID_APPLICATION: 141 | project.android.metaClass.applicationVariants = variants 142 | // mock .all{ } function from android gradle lib with standard groovy .each{ } 143 | project.android.applicationVariants.metaClass.all = { delegate.each(it) } 144 | break 145 | case ProjectType.ANDROID_LIBRARY: 146 | case ProjectType.ANDROID_DYNAMIC_FEATURE: 147 | project.android.metaClass.libraryVariants = variants 148 | // mock .all{ } function from android gradle lib with standard groovy .each{ } 149 | project.android.libraryVariants.metaClass.all = { delegate.each(it) } 150 | break 151 | } 152 | 153 | return this 154 | } 155 | 156 | Project get() { 157 | return project 158 | } 159 | 160 | enum ProjectType { 161 | ANDROID_APPLICATION('com.android.application'), 162 | ANDROID_KOTLIN_APPLICATION('com.android.application', 'org.jetbrains.kotlin.android'), 163 | ANDROID_KOTLIN_MULTIPLATFORM('com.android.library', 'org.jetbrains.kotlin.multiplatform'), 164 | ANDROID_LIBRARY('com.android.library'), 165 | ANDROID_DYNAMIC_FEATURE('com.android.dynamic-feature'), 166 | ANDROID_TEST('com.android.test'), 167 | JAVA('java'), 168 | ROOT(null) 169 | 170 | private final String[] pluginNames 171 | 172 | ProjectType(String... pluginNames) { 173 | this.pluginNames = pluginNames 174 | } 175 | } 176 | } 177 | --------------------------------------------------------------------------------