Saturday 30 October 2021

Robolectric + JaCoCo | Issue while running unit test and not generating code coverage

I have added Robolectric to get support of Shadow APIs for writing unit tests. Able to get coverage percentage through default Intellij code coverage tool in Android Studio.

Now trying to add JaCoCo to get enhanced coverage report.

I'm using file build.gradle(app) for putting
plugin as apply from: "$rootDir/jacoco.gradle" and
dependency as testImplementation 'org.robolectric:robolectric:4.3.1'


jacoco.gradle

apply plugin: 'jacoco'

/*jacoco {
    // https://bintray.com/bintray/jcenter/org.jacoco:org.jacoco.core
    toolVersion = "0.7.1.201405082137"
}*/

android {
    testOptions {

        unitTests {
            includeAndroidResources = true
        }

        unitTests.all {
            systemProperty 'user.home', System.getenv('HOME')
            jacoco {
                includeNoLocationClasses = true
            }
        }

        unitTests {
            returnDefaultValues = true
        }
    }
}

project.afterEvaluate {

    android.applicationVariants.all { variant ->
        def name = variant.name
        def testTaskName = "test${name.capitalize()}UnitTest"

        tasks.create(name: "${testTaskName}Coverage", type: JacocoReport, dependsOn: "$testTaskName") {
            group = "Reporting"
            description = "Generate Jacoco coverage reports for the ${name.capitalize()} build."

            classDirectories.from = fileTree(
                    dir: "${project.buildDir}/intermediates/classes/${name}",
                    excludes: ['**/R.class',
                               '**/R$*.class',
                               '**/*$ViewInjector*.*',
                               '**/*$ViewBinder*.*',
                               '**/BuildConfig.*',
                               '**/Manifest*.*']
            )

            sourceDirectories.from = files(['src/main/java'].plus(android.sourceSets[name].java.srcDirs))
            executionData.from = files("${project.buildDir}/jacoco/${testTaskName}.exec")

            reports {
                xml.enabled = true
                html.enabled = true
            }
        }
    }
}

While running test cases through CL/Run(Button) or Jenkins, getting same error

com.example.LoginActivityTest > initializationError FAILED
    java.lang.RuntimeException at AndroidJUnit4.java:121
        Caused by: java.lang.reflect.InvocationTargetException at null:-1
            Caused by: java.lang.NoSuchMethodError at ShadowProviders.java:25

com.example.HomeActivityTest > initializationError FAILED
    java.lang.RuntimeException at AndroidJUnit4.java:121
        Caused by: java.lang.reflect.InvocationTargetException at null:-1
            Caused by: java.lang.NoSuchMethodError at ShadowProviders.java:25

I appreciate your help!



from Robolectric + JaCoCo | Issue while running unit test and not generating code coverage

No comments:

Post a Comment