junit testing with gradle for an android project - android

I am trying to get tests ( junit and robolectric ) working in an Android project but am totally stuck. My main problem is that all testing I found with gradle somehow pull in the java plugin and then I get this error:
The 'java' plugin has been applied, but it is not compatible with the Android plugins.
The only way out I see at the moment is to split into test and app project - but I would like to avoid that. Any examples/hints would be highly appreciated!
In the official documentation there is no mention of unit-testing - only Instrumentation-Tests - but I want unit-tests to get results fast.

You don't need the Java plugin, since the Android will take care of what you need mostly, from what I've seen so far.
I managed to get my Robolectric and junit tests running via this man's blog: http://tryge.com/2013/02/28/android-gradle-build/
My build.gradle file looks like this (where my test files are in the {projectdir}/test directory.
...
// Unit tests
sourceSets {
unitTest {
java.srcDir file('test')
resources.srcDir file('test/resources')
}
}
dependencies {
unitTestCompile files("$project.buildDir/classes/debug")
unitTestCompile 'junit:junit:4.11'
unitTestCompile 'org.robolectric:robolectric:2.1.1'
unitTestCompile 'com.google.android:android:4.0.1.2'
}
configurations {
unitTestCompile.extendsFrom runtime
unitTestRuntime.extendsFrom unitTestCompile
}
task unitTest(type:Test, dependsOn: assemble) {
description = "run unit tests"
testClassesDir = project.sourceSets.unitTest.output.classesDir
classpath = project.sourceSets.unitTest.runtimeClasspath
}
build.dependsOn unitTest

AndroidStudio and the new Android Gradle plugin are now offering official unit test support.
This is supported from Android Studio 1.1+ and Android Gradle plugin version 1.1.0+
Dependencies can now be declared as testCompile:
dependencies {
testCompile 'junit:junit:4.12'
testCompile "org.mockito:mockito-core:1.9.5"
}
More details here: Unit testing support - Android Tools Project Site.

This guide might help -
http://www.slideshare.net/tobiaspreuss/how-to-setup-unit-testing-in-android-studio
Latest gradle the test should be under androidTest dir
Also in your gradle.build:
dependencies {
androidTestCompile 'junit:junit:4.+'
}
also add those under defaultConfig {
testPackageName "test.java.foo"
testInstrumentationRunner "android.test.InstrumentationTestRunner"
}

This is what worked for me only:
androidTestCompile 'net.bytebuddy:byte-buddy-android:0.7.8'

You should use this doc
https://developer.android.com/training/testing/unit-testing/local-unit-tests.html
It describes non-instrumentation unit tests that run on developer machine, not on android device.

Related

Unable to resolve Android JUnit test runner

I am trying to add an instrumentation test to our project, but it seems that Gradle doesn't properly add the Android JUnit Test Runner to the project's classpath. The test depenencies of my gradle build file looks like this:
testCompile 'junit:junit:4.12'
androidTestCompile 'junit:junit:4.12'
androidTestCompile 'com.android.support.test:runner:0.5'
androidTestCompile 'com.android.support.test.espresso:espresso-core:2.2.2'
We are using the latest version of the support library (24.0.0), but the current version of the test runner (JUnit runner) and Espresso use version 23.1.0. To resolve the version conflict, I force the runner (and Espresso) to use the newer version (I understand the implications, but we can't use the older version):
androidTestCompile 'com.android.support:support-v4:24.0.0'
androidTestCompile 'com.android.support:appcompat-v7:24.0.0'
androidTestCompile 'com.android.support:support-v13:24.0.0'
androidTestCompile 'com.android.support:recyclerview-v7:24.0.0'
androidTestCompile 'com.android.support:design:24.0.0'
androidTestCompile 'com.android.support:support-annotations:24.0.0'
and:
configurations.all {
resolutionStrategy {
force 'com.android.support:support-annotations:24.0.0'
}
}
However, for some reason, Gradle doesn't add the runner package (under android.support.test). So
import android.support.test.runner.AndroidJUnit4;
throws an error: cannot resolve symbol 'runner'. Have cleared Android Studio's cache, restarted the IDE, cleared Gradle's cache (both project and global), all with no luck. Does anyone know what's going on?
try adding:
androidTestCompile 'com.android.support.test:rules:0.5'
This is my old question but thought it might help to explain the issue and the solution. The issue was with the name of the debug build variant: if you name your debug build variant anything but debug, make sure to notify Android's Gradle plugin by adding testBuildType "yourDebugBuildVariantName" to your build.gradle script (your app module's build.gradle not the project global) in the android{} section, or rename your debug build variant to just debug. If you have multiple debug build variants, you need to specify one of them on which you'd like to run your tests, like: testBuildType armDebug:
apply plugin: 'com.android.application'
...
android {
testBuildType "myDebug" <-
compileOptions { ... }
sourceSets { ... }
signingConfigs { ... }
}
Even with this explicit config, Gradle occasionally seems to have issues with running instrumentation tests. The best way to workaround this is to rename your debug build variant (the one you run your tests on) to debug if this is a feasible option for you.

Instrumented Tests in Android Studio

I have been trying to run simple instrumented tests in Android Studio, without any success.
I followed the guide for Unit Tests and it works fine. Now, I would like to tests components which are difficult to mock.
When I follow the guide on instrumented tests, I end up with dependency errors.
What I did:
Install the Android Testing Support Library (Android Support Repository, rev 17).
Create a directory androidTest in src. Add Java folder + package ending with "test".
Add a simple Test class
#RunWith(AndroidJUnit4.class)
public class ServerRequestInstrumentationTest {
#Test
public void test(){
LogC.d("Here we go testing !");
}
}
Add a simple TestSuit.
#RunWith(Suite.class)
#Suite.SuiteClasses({ServerRequestInstrumentationTest.class})
public class TestSuit {
public TestSuit(){}
}
Modify my gradle file to add dependencies.
apply plugin: 'com.android.application'
android {
compileSdkVersion 22
buildToolsVersion "22.0.1"
defaultConfig {
applicationId "com.mydomain.app"
minSdkVersion 9
targetSdkVersion 22
versionCode 28
versionName "2.0.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_7
targetCompatibility JavaVersion.VERSION_1_7
}
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
lintOptions {
disable 'MissingTranslation'
}
}
}
sourceSets { main { java.srcDirs = ['src/main/java'] } }
}
dependencies {
compile 'com.android.support:support-v4:22.2.0'
compile 'com.android.support:appcompat-v7:22.2.0'
wearApp project(':wear')
compile project(':moreapps')
compile project(':lib_repair')
compile project(':bugreport')
//testCompile 'junit:junit:4.12'
testCompile 'org.mockito:mockito-core:1.10.19'
androidTestCompile 'junit:junit:4.12'
androidTestCompile 'org.hamcrest:hamcrest-library:1.1'
androidTestCompile 'com.android.support.test:runner:0.3'
androidTestCompile 'com.android.support.test:rules:0.3'
}
I just added the line androidTestCompile 'junit:junit:4.12', otherwise the annotation #RunWith(AndroidJUnit4.class) wasn't recognized.
Now when I launch the test, I get one Gradle build error.
Error:Execution failed for task ':app:dexDebugAndroidTest'.
com.android.ide.common.process.ProcessException: org.gradle.process.internal.ExecException: Process 'command
'/usr/lib/jvm/jdkoracle/bin/java'' finished with non-zero exit value 2
Any suggestion ? Did I miss something about the testing library ?
Thank you
Okay, finally got it working.
After a little search, I found out that the Gradle console output an error :
AGPBI: {"kind":"simple","text":"UNEXPECTED TOP-LEVEL EXCEPTION:","sources":[{}]}
AGPBI: {"kind":"simple","text":"com.android.dex.DexException: Multiple dex files define Lorg/hamcrest/TypeSafeMatcher;","sources":[{}]}
After I changed one line in my gradle build, Gradle built the project successfuly and I was able to run the simple instrumented test.
Line to change:
androidTestCompile 'org.hamcrest:hamcrest-library:1.1'
to
testCompile 'org.hamcrest:hamcrest-library:1.1'
I don't know why Gradle complains in one case and not the other though...
Instrumentation tests are different to Unit Tests. You have to extend your test classes by specific classes. For more information about that take a look at Android Testing Fundamentals. Also you do not need JUnit for Instrumentaion tests.
Furthermore you have to switch your build variants from Unit Tests to Android Instrumentation Tests, as described here Unit testing in android studio
EXAMPLE:
Here an example for an instrumentaion test in android:
public class ExampleITest extends AndroidTestCase {
#Override
public void setUp() throws Exception {
super.setUp();
InputStream is = getContext().getAssets().open("test.xml");
XmlParser parser = new XmlParser(getContext());
parser.parse(is);
...
}
#MediumTest
public void testSomething() throws Exception {
// test some data your parser extracted from the xml file
...
}
}
As you can see, you can access context, etc.
For this test no specific dependencies are necessary in the gradle file.
I haven't heard about Instrumantation tests just with annotions. maybe i should look it up on the web ;)
Althought #Gordark's answer will not throw any error It's not a proper solution if you want to use Hamcrest in your instrumentation tests, it will work just for your local JVM tests.
I found that using 1.3 version of hamcrest-library actually worked, just replace
androidTestCompile 'org.hamcrest:hamcrest-library:1.1'
with
androidTestCompile 'org.hamcrest:hamcrest-library:1.3'
And it should work. I think it's something about conflicting versions of junit and hamcrest. I guess hamcrest 1.1 depends on a version of junit bellow 4.12, and hamcrest 1.3 depends on junit v4.12
Your answer contains a hint to the problem. You state there that Gradle gives an error. This is because one of the other dependencies for androidTestCompile depends on hamcrest. This is called a transitive dependency. It also means that you can completely remove your explicit requirement for hamcrest. Your change adds hamcrest as a dependency for testCompile which is used for unit tests run locally on your development machine rather than on an Android device or emulator. If you aren't making unit tests you don't need this. Even when you do start writing unit tests, you probably don't need an explicit dependency on hamcrest.

How to setup the robolectric in Android Studio

I am doing work to test my android application using unit framework robolectric. I have installed the Android Studio (.4.6)
All blogs saying for this "In order to be able to run Android unit tests with Gradle, we need to add the Gradle Android Test plug-in to the build script."
but that is deprecated now then how can I setup this without using this or I have to use this.
I am using com.github.jcandksolutions.gradle:android-unit-test:+
So in your root build.gradle (buildscript section):
repositories {
mavenLocal()
mavenCentral()
maven { url 'https://oss.sonatype.org/content/repositories/snapshots/' }
}
dependencies {
classpath 'com.android.tools.build:gradle:0.8.+'
classpath 'com.github.jcandksolutions.gradle:android-unit-test:+'
}
In your app's build.gradle
apply plugin: 'android'
android {
[...]
sourceSets {
// this sets the root test folder to src/test overriding the default src/instrumentTest
instrumentTest.setRoot('src/test')
}
}
apply plugin: 'android-unit-test'
dependencies {
// example dependencies
instrumentTestCompile 'junit:junit:4.+'
instrumentTestCompile 'org.robolectric:robolectric:2.3-SNAPSHOT'
testCompile 'junit:junit:4.+'
testCompile 'org.robolectric:robolectric:2.3-SNAPSHOT'
}
Note that you have to declare the dependency twice (one for instrumentTestCompile scope and one for testCompile scope (for android-unit-test plugin)). This is necessary at least for this version of Android Studio and the plugin.
Then you can run tests with gradlew test from terminal (either in Android Studio or standalone).
Side note 1: I had some problems with Android Studio terminal integration on Windows. It did not handle well the limited horizontal space available, truncating the output. As a result I started using ConEmu, avoiding the embedded terminal in Android Studio and the standard cmd.exe.

How to run unit tests with Android Studio

I'm using Jake's Android unit tests plugin for gradle: https://github.com/JakeWharton/gradle-android-test-plugin
My build.gradle looks like this:
dependencies {
// analytics
compile('com.crittercism:crittercism-android:3.0.11')
// retrofit
compile('com.squareup.retrofit:retrofit:1.2.2')
compile('com.squareup.okhttp:okhttp:1.2.1')
// dagger
compile('com.squareup.dagger:dagger:1.1.0')
compile('com.squareup.dagger:dagger-compiler:1.1.0')
// compatibility
compile('android.compatibility:android-support:v4-r13')
compile('com.actionbarsherlock:actionbarsherlock:4.4.0#aar')
// Picasso
compile('com.squareup.picasso:picasso:2.1.1')
// Otto
compile('com.squareup:otto:1.3.4')
// Tests
testCompile 'junit:junit:4.10'
testCompile 'org.robolectric:robolectric:2.2'
testCompile 'org.powermock:powermock-api-mockito:1.5.1'
testCompile 'org.easytesting:fest-assert-core:2.0M10'
}
Unfortunately I'm not able to run all or specific unit test form Android Studio. I'm getting error:
Exception in thread "main" java.lang.NoClassDefFoundError: junit/textui/ResultPrinter
at java.lang.Class.forName0(Native Method)
at java.lang.Class.forName(Class.java:171)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:113)
Caused by: java.lang.ClassNotFoundException: junit.textui.ResultPrinter
at java.net.URLClassLoader$1.run(URLClassLoader.java:202)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:190)
at java.lang.ClassLoader.loadClass(ClassLoader.java:306)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:301)
at java.lang.ClassLoader.loadClass(ClassLoader.java:247)
... 3 more
And this is correct because running command line doesn't include my JUnit dependency:
/System/Library/Java/JavaVirtualMachines/1.6.0.jdk/Contents/Home/bin/java -ea -Didea.launcher.port=7533 "-Didea.launcher.bin.path=/Applications/Android Studio.app/bin" -Dfile.encoding=UTF-8 -classpath "/Applications/Android Studio.app/lib/idea_rt.jar:/Applications/Android Studio.app/plugins/junit/lib/junit-rt.jar:/Users/eugen/Development/SDK/android-sdk-macosx/platforms/android-18/android.jar:/Users/eugen/Development/SDK/android-sdk-macosx/platforms/android-18/data/res:/Users/eugen/Development/SDK/android-sdk-macosx/tools/support/annotations.jar:/Users/eugen/Development/Projects/eBuddy/xms/android/xms3-android/build/classes/alpha/debug:/Users/eugen/.gradle/caches/artifacts-26/filestore/com.squareup.retrofit/retrofit/1.2.2/jar/cdf7b60568092fbcc7a254371c345e92f733c03c/retrofit-1.2.2.jar:/Users/eugen/.gradle/caches/artifacts-26/filestore/com.google.code.gson/gson/2.2.4/jar/a60a5e993c98c864010053cb901b7eab25306568/gson-2.2.4.jar:/Users/eugen/.gradle/caches/artifacts-26/filestore/com.squareup.okhttp/okhttp/1.2.1/jar/c3562574496bb4d452d6fc45b817577e98d08afe/okhttp-1.2.1.jar:/Users/eugen/.gradle/caches/artifacts-26/filestore/com.squareup/javawriter/2.1.1/jar/67ff45d9ae02e583d0f9b3432a5ebbe05c30c966/javawriter-2.1.1.jar:/Users/eugen/.gradle/caches/artifacts-26/filestore/com.squareup.dagger/dagger/1.1.0/jar/49f2061c938987c8e56679a731d74fd8448d8742/dagger-1.1.0.jar:/Users/eugen/.gradle/caches/artifacts-26/filestore/com.squareup.picasso/picasso/2.1.1/jar/ab19bfb23f641f189b6dca9a4d393f8dc291103a/picasso-2.1.1.jar:/Users/eugen/.gradle/caches/artifacts-26/filestore/com.squareup/otto/1.3.4/jar/4d72fb811c7b3c0e7f412112020d4430f044e510/otto-1.3.4.jar:/Users/eugen/.gradle/caches/artifacts-26/filestore/com.squareup.dagger/dagger-compiler/1.1.0/jar/ddb38c2be31deeb7a001177f7c358665e350d646/dagger-compiler-1.1.0.jar:/Users/eugen/.gradle/caches/artifacts-26/filestore/javax.inject/javax.inject/1/jar/6975da39a7040257bd51d21a231b76c915872d38/javax.inject-1.jar:/Users/eugen/Development/Projects/eBuddy/xms/android/xms3-android/build/exploded-bundles/ComActionbarsherlockActionbarsherlock440.aar/res:/Users/eugen/Development/Projects/eBuddy/xms/android/xms3-android/build/exploded-bundles/ComActionbarsherlockActionbarsherlock440.aar/classes.jar:/Users/eugen/.gradle/caches/artifacts-26/filestore/com.squareup.okhttp/okhttp-protocols/1.2.1/jar/ec2beaefef3bd4f680c17fad8e72e66f2a006f1/okhttp-protocols-1.2.1.jar:/Users/eugen/.gradle/caches/artifacts-26/filestore/com.crittercism/crittercism-android/3.0.11/jar/e30c21ae491d780622ecaee2752969be98140c3/crittercism-android-3.0.11.jar:/Users/eugen/.gradle/caches/artifacts-26/filestore/android.compatibility/android-support/v4-r13/jar/bd6479f5dd592790607e0504e66e0f31c2b4d308/android-support-v4-r13.jar" com.intellij.rt.execution.application.AppMain com.intellij.rt.execution.junit.JUnitStarter -ideVersion5 #/private/var/folders/wq/knhztnf105v2_p1t580tj8h80000gp/T/idea_junit701450667388095664.tmp #w#/private/var/folders/wq/knhztnf105v2_p1t580tj8h80000gp/T/idea_working_dirs_junit4927192380605663413.tmp -socket63849
I wonder if anyone was able to run unit tests in Android Studio? And if it is possible how make it?
just add folder named instrumentTest under /src
it should have /java inside like this
then extend the class ActivityTestCase (or any other android unit-test-class), such as
package com.example.app.test;
import android.test.ActivityTestCase;
import junit.framework.Assert;
public class MainActivityTest extends ActivityTestCase {
public void testHappy(){
Assert.assertTrue(true);
}
}
right click on green java directory and select run all tests
and you should get this:
good luck
Update for AS 1.1+, android gradle plugin 1.1+
Finally it is possible without many tricks. Here is example of project that shows how to setup Robolectric test in Android Studio v1.1+ and android gradle plugin v1.1+:
https://github.com/nenick/AndroidStudioAndRobolectric
You can find also there possible issue and workarounds. Yes, Robolectric is complex and not officially supported by Google so it still has some issues. But most of the time it works and brings huge value to your project.
I would also encourage you to start using Robolectric v3+. It is almost released and stable enough.
Old answer for AS 0.x and 1.0x and android gradle plugin version below 1.1
I managed to make it with help of friends.
So basically you need to make next changes to run Robolectric unit tests in Android Studio:
Copy your classpath for test (you can find it as first line in "Run" log)
Open run configuration for your unit tests
Change working dir to folder where AndroidManifest.xml is present
Add VM Option -classpath "<path_to_project_folder>/build/test-classes:<path_to_gradle_cache>/caches/modules-2/files-2.1/junit/junit/4.11/4e031bb61df09069aeb2bffb4019e7a5034a4ee0/junit-4.11.jar:<your old classpath>"
As for me the start of new classpath looks like this:
/Users/emartynov/Development/Projects/work/android.project/build/test-classes:/Users/emartynov/.gradle/caches/modules-2/files-2.1/junit/junit/4.11/4e031bb61df09069aeb2bffb4019e7a5034a4ee0/junit-4.11.jar
Problems:
You can run test only for debug variant
Every new test run configuration requires such manual changes. But this is simply copy/paste of two edit fields
I have Android Studio 0.6 version. Here is again part of my build.gradle file:
buildscript {
repositories {
mavenCentral()
maven { url 'https://github.com/rockerhieu/mvn-repo/raw/master/' }
}
dependencies {
classpath 'com.android.tools.build:gradle:0.11.+'
classpath 'com.neenbedankt.gradle.plugins:android-apt:1.3'
// classpath 'org.robolectric.gradle:gradle-android-test-plugin:0.10.1'
classpath 'org.robolectric.gradle:gradle-android-test-plugin:0.10.1-SNAPSHOT'
classpath 'com.jakewharton.sdkmanager:gradle-plugin:0.10.+'
}
}
apply plugin: 'android-sdk-manager'
apply plugin: 'android'
apply plugin: 'android-apt'
apply plugin: 'android-test'
repositories {
mavenCentral()
}
android {
compileSdkVersion 19
buildToolsVersion "19.1.0"
packagingOptions {
exclude 'META-INF/NOTICE'
exclude 'META-INF/NOTICE.txt'
exclude 'META-INF/notice.txt'
exclude 'META-INF/LICENSE'
exclude 'META-INF/LICENSE.txt'
exclude 'META-INF/license.txt'
exclude 'META-INF/ASL2.0'
exclude 'LICENSE.txt'
}
defaultConfig {
minSdkVersion 14
targetSdkVersion 19
versionCode 1
versionName "0.9.0"
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_7
targetCompatibility JavaVersion.VERSION_1_7
}
sourceSets {
androidTest.setRoot( 'src/test' )
}
}
dependencies {
// butter knife
compile 'com.jakewharton:butterknife:5.0.0'
// dagger
compile 'com.squareup.dagger:dagger:1.2.1'
// apt
apt 'com.squareup.dagger:dagger-compiler:1.+'
// AS tests
androidTestCompile 'junit:junit:4.+'
androidTestCompile( 'org.robolectric:robolectric:2.3' ) {
exclude group: 'commons-logging'
exclude group: 'org.apache.httpcomponents'
}
androidTestCompile 'com.squareup:fest-android:1.+'
androidTestCompile 'org.mockito:mockito-all:1.9.+'
androidTestCompile 'org.easytesting:fest-assert-core:2.0M10'
androidTestCompile( 'org.skyscreamer:jsonassert:1.2.+' ) {
exclude group: 'org.json'
}
// tests
testCompile 'junit:junit:4.+'
testCompile( 'org.robolectric:robolectric:2.3' ) {
exclude group: 'commons-logging'
exclude group: 'org.apache.httpcomponents'
}
testCompile 'com.squareup:fest-android:1.+'
testCompile 'org.mockito:mockito-all:1.9.+'
testCompile 'org.easytesting:fest-assert-core:2.0M10'
testCompile 'com.squareup.dagger:dagger-compiler:1.+'
testCompile( 'org.skyscreamer:jsonassert:1.2.+' ) {
exclude group: 'org.json'
}
}
I ran into this problem and found a solution - include the classes.jar from the exploded bundle (.aar) in the build folder. I don't think will help with finding resources in .aar dependencies though.
testCompile fileTree(dir: "$project.buildDir/exploded-bundles", include: "**/classes.jar")
Edit: Since Android Gradle build tools 0.9.0 the dependency has changed to:
androidTestCompile fileTree(dir: "$project.buildDir/exploded-aar", include: "**/classes.jar")
Edit 2: Since Android Gradle build tools 0.10.0 the dependency has changed to:
androidTestCompile fileTree(dir: "$project.buildDir/../../build/exploded-aar", include: "**/classes.jar")
Note: the relative path may be different depending on your project structure.
For posterity Android Studio 2.0+ supports running Unit tests without plugins.
This screen can be accessed through menu Run > Edit Configurations...
I had a similar problem with AS 1.2.2.
I followed the steps here. Basically:
Opened the "Build Variants" tool window (see image on the link) and changed the "Test Artifact" drop-down to "Unit tests".
Create a directory for your testing source code, i.e. src/test/java, and move your test to the respective package there.
Make sure the following sections of your build.gradle file contain these:
dependencies {
testCompile 'junit:junit:4.12'
}
android {
sourceSets {
test {
resources {
srcDir "test"
}
}
}
}
Voila! Right-click your test case and select the JUnit flavor.
BTW, it seems to toggle the visibility of the JUnit/Android tests when you change the "Build Variants" tool, so my guess is you can either test as JUnit or Android but not both at same time.

Android Gradle Code Coverage

I have a simple android project with test cases.
ProjNameProject
--build.gradle
--ProjName
----build.gradle
I see that by default android's new build system provides basic test results by default. (Hooray!)
Now I want to see code coverage as well. I know how to set this up using Emma and Ant scripts, however I don't want to run Ant scripts here. I feel that would defeat the purpose of me using the new build system.
I've tried a few Cobertura plugins that were found on Github. One in particular:
https://github.com/stevesaliman/gradle-cobertura-plugin
However if I try to use the plugin in the ProjName build file then I get errors about the java plugin. I read on tools.android.com that adding the java plugin will generate this behavior. I'm not applying it so the cobertura plugin must be.If I try to use the plugin in the main build file then I don't see the java errors but now i see:
Could not find net.sourceforge.cobertura:cobertura:1.9.4.1.
Required by:
:ProjNameProject:unspecified
What do I do??
JaCoCo support was added to the Android gradle plugin v0.10 (http://tools.android.com/tech-docs/new-build-system).
Enable in the tested Build Type with testCoverageEnabled = true
android {
jacoco {
version = '0.6.2.201302030002'
}
}
I was able to get JaCoCo coverage working with Robolectric by following http://chrisjenx.com/gradle-robolectric-jacoco-dagger/.
apply plugin: 'android'
apply plugin: 'robolectric'
apply plugin: 'jacoco'
dependencies {
compile fileTree(dir: 'libs', include: '*.jar')
compile 'com.android.support:appcompat-v7:19.1.+'
androidTestCompile fileTree(dir: 'libs/test', include: '*.jar')
androidTestCompile 'junit:junit:4.11'
androidTestCompile 'org.robolectric:robolectric:2.3'
androidTestCompile 'com.squareup:fest-android:1.0.+'
}
robolectric {
// Configure the set of classes for JUnit tests
include '**/*Test.class'
exclude '**/*AbstractRobolectricTestCase.class'
// Configure max heap size of the test JVM
maxHeapSize = "2048m"
}
jacoco {
toolVersion = "0.7.1.201405082137"
}
//Define coverage source.
//If you have rs/aidl etc... add them here.
def coverageSourceDirs = [
'src/main/java',
'src/gen'
]
...
// Add JaCoCo test reporting to the test task
// http://chrisjenx.com/gradle-robolectric-jacoco-dagger/
task jacocoTestReport(type: JacocoReport, dependsOn: "testDebug") {
group = "Reporting"
description = "Generate Jacoco coverage reports after running tests."
reports {
xml.enabled = true
html.enabled = true
}
// Class R is used, but usage will not be covered, so ignore this class from report
classDirectories = fileTree(
dir: './build/intermediates/classes/debug',
excludes: ['**/R.class',
'**/R$*.class'
])
sourceDirectories = files(coverageSourceDirs)
executionData = files('build/jacoco/testDebug.exec')
}
Emma support is planned to be released soon within the new Android build system : http://tools.android.com/tech-docs/new-build-system/roadmap
Up to now there is no official way to run emma with android via gradle. I guess instrumenting can be achieved pretty easily but then, you will miss a way to tell Android to run tests with coverage on. Moreover, there is currently no way (to the best of my knowledge) to pull down emma runtime coverage data from the device.
This project can interest you : https://github.com/stephanenicolas/Quality-Tools-for-Android. It will be updated as soon as emma will make it into Android Gradle plugin.
----UPDATE
This plugin has no chance to work with Android has it uses the Java plugin which is incompatible with Android plugin.

Categories

Resources