Android studio code coverage not showing any Kotlin classes - android

I have 2 Kotlin based AS projects. One works fine, the other doesn't. Both have an identical structure and gradle config. I'm using Kotlin 1.1.4-2 with AS 3.0b2.
The problem is that when I run code coverage, the classes I'm testing do not even show up under the coverage report. The only thing I see is R.java and BuildConfig.java, but none of my source files are being found.
All source files are Kotlin based. I'm using Spek for my unit testing. Same setup and versions as my other functional project. I tried using both JaCoCo and Jetbrains code coverage and neither works.
I apologize, I'm not able to embed pictures yet.
This is the problem:
Here's my project structure:
And here's my gradle android block:
compileSdkVersion 26
buildToolsVersion "26.0.1"
defaultConfig {
minSdkVersion 16
targetSdkVersion 26
versionCode 1
versionName libraryVersion
}
buildTypes {
debug {
testCoverageEnabled = true
}
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
and my dependencies:
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation "org.jetbrains.kotlin:kotlin-stdlib-jre7:$kotlin_version"
implementation "io.reactivex.rxjava2:rxkotlin:2.1.0"
testImplementation 'junit:junit:4.12'
testImplementation "org.jetbrains.kotlin:kotlin-test:$kotlin_version"
testImplementation 'org.jetbrains.spek:spek-api:1.1.2'
testImplementation 'org.jetbrains.spek:spek-junit-platform-engine:1.1.2'
testImplementation 'org.junit.platform:junit-platform-runner:1.0.0-M4'
testImplementation 'org.junit.jupiter:junit-jupiter-api:5.0.0-M4'
implementation 'com.android.support:appcompat-v7:26.0.1'
implementation 'com.squareup.okhttp3:okhttp-ws:3.3.1'
implementation 'com.google.protobuf:protobuf-java:2.6.1'
I've tried running
task copyTestClasses(type: Copy) {
from "build/tmp/kotlin-classes/debugUnitTest"
into "build/intermediates/classes/debug"
}
task copySdkClasses(type: Copy) {
from "build/tmp/kotlin-classes/debug"
into "build/intermediates/classes/debug"
}
before my testing and that doesn't work either.
What's strange is my other project, using the same AS version, Kotlin version, and project structure, is working fine and generating proper code coverage.
Any help would be appreciated.

Try to use JaCoco for coverage, this is a IntelliJ IDEA issue: Kotlin inline keyword causing IntelliJ IDEA Coverage reporting 0%
How to use JaCoco to get the coverage:
Making Android Studio Test Coverage works
Resume:
Click on edit configurations
Go to Run/Debug Configurations -> Defaults -> Android JUnit -> Code Coverage
Choose coverage Runner: Select JaCoCo
Apply -> OK
Run your test again and voila you will get the coverage

Kotlin announced the new kotlinx-kover Gradle plugin compatible with JaCoCo and IntelliJ.
It resolves the problem with inline functions and maybe more.
plugins {
id("org.jetbrains.kotlinx.kover") version "0.5.0"
}
Once applied, the plugin can be used out of the box without additional configuration.
Watch its YouTube announcement video and also track its roadmap from this youtrack issue.

Related

Can Not Perform Copy-Paste in Android Studio

I have faced two main problems in Android Studio. First of all I can not perform copy-paste and cut-paste (ctrl+c - ctrl+v - ctrl+x) abilities in some classes. To fix that problem, I click "invalide caches/restarts", but it breaks down again immediately.
Second problem is (I think it is related to the first problem) compiler does not recognize already defined methods and attributes. Auto suggestion etc. does not work.
The steps I've taken to try to fix the problem are;
File -> invalide caches/restarts,
File -> Power Save Mode -> Disable,
Close all opened tabs and fresh restart,
File -> Sync Project with Gradle Files,
File -> Sync with File System,
Delete JDK and reinstall,
Delete Android Studio and reinstall,
Delete already downloaded SDK files and ".Android" folder,
Disable and delete all plugins.
Checked copy-paste keymap in File -> Settings -> Keymap
Pulled the project from bitbucket to different 2 computers
Created new project, copy whole project classes with NotePad++ to
new Project
Try to convert all Java codes to Kotlin, cannot convert
Here is my system specifications; Windows 10 Home Single Language (TR), version 1909. 16 GB ram. Android Studio 3.5.3 and Gradle Version 3.5.3
I have read all post about the same problem but there is no luck (The posts are only about MAC and Linux platform).
UPDATE 1.0 ->
I have discovered that some classes cannot do the operations described above, but some classes can.
I realized that, There are no icons for classes that cannot do the operations I have described above. (Sometimes magically appears "J" icons and when I clicked another class, this J icon disappears immediately.) I think gradle or file system of Android Studio does not recognize these files as classes.
UPDATE 2.0 ->
I have noticed that when I clicked the Structure section of DuoFragment (Which has 500+ lines codes and one of the uncompiled class) cannot load anything. Is DuoFragment size is bigger to process?
Also when I checked the Build section, some processes cannot run (I do not know if this is normal or not);
Task :app:compileDebugAidl NO-SOURCE,
Task :app:compileDebugRenderscript NO-SOURCE,
Task :app:processDebugJavaRes NO-SOURCE
UPDATE 3.0 ->
Here are my Gradle files.
Project Level Gradle file :
// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
repositories {
google()
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:3.5.3'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
allprojects {
repositories {
google()
jcenter()
maven { url 'https://jitpack.io' }
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}
App level Gradle file.
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
android {
compileSdkVersion 29
buildToolsVersion "29.0.2"
defaultConfig {
applicationId "com.lotusif.dump2"
minSdkVersion 21
targetSdkVersion 29
versionCode 1
versionName "1.0"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility = 1.8
targetCompatibility = 1.8
}
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'androidx.appcompat:appcompat:1.1.0'
implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
implementation 'androidx.recyclerview:recyclerview:1.1.0'
implementation 'androidx.core:core:1.1.0'
// material widgets
implementation 'com.google.android.material:material:1.2.0-alpha03'
// progress bar with text
implementation "com.github.skydoves:progressview:1.0.3"
// sequence progress
implementation 'com.github.transferwise:sequence-layout:1.0.11'
// flash bar
implementation 'com.andrognito.flashbar:flashbar:1.0.2'
// toggle - switch button
implementation 'com.github.GwonHyeok:StickySwitch:0.0.15'
// Custom Toast message
implementation 'com.github.GrenderG:Toasty:1.4.2'
// liquid effect bar
implementation 'com.mikhaellopez:circularfillableloaders:1.3.2'
// bubble tab bar
implementation 'com.fxn769:bubbletabbar:1.0.3'
//glide image library
implementation 'com.github.bumptech.glide:glide:4.10.0'
annotationProcessor 'com.github.bumptech.glide:compiler:4.10.0'
// scaling layout
implementation 'com.github.iammert:ScalingLayout:1.2.1'
// lottie animation
implementation 'com.airbnb.android:lottie:3.3.1'
//Gson
implementation 'com.google.code.gson:gson:2.8.6'
//RxJava
implementation 'io.reactivex.rxjava2:rxjava:2.2.15'
implementation 'io.reactivex.rxjava2:rxandroid:2.0.1'
implementation 'com.daimajia.easing:library:2.1#aar'
implementation 'com.daimajia.androidanimations:library:2.3#aar'
//retrofit
implementation 'com.squareup.retrofit2:converter-gson:2.7.1'
implementation 'com.squareup.retrofit2:retrofit:2.7.1'
implementation 'com.squareup.retrofit2:adapter-rxjava2:2.7.1'
}
UPDATE 1.0 Images
UPDATE 2.0 Images
UPDATE --> There is a bug in Kotlin libraries with Windows 10 Single Language Turkish. (Maybe some of other Single Language Windows distributions have same issue, I haven't known yet.) Kotlin's some libraries cannot work on Turkish operating system. I solved this problem with installing Windows 10 Pro English.
Other developers who use Windows 10 Single Language Turkish faces same problem with different angles. (Example1 and Example2)
OLD ANSWER
TL;DR -> Problem is about third party libraries that are written with Kotlin. I have converted my Java project to Kotlin and all problematic third party libraries work well. Problem is about Java - Kotlin conflict.
I would like to share how I solved the problem for those who will face such problems later.
I did all the steps I mentioned above one by one but I could not find any solution and I decided to examine my third party libraries.
First of all, I disabled all third party libraries and looked at the status of my classes that did not recognize already defined methods and attributes. After disabling third party libraries and making Rebuild Project and Sync Gradle, the Auto Suggestion feature of those corrupted classes started working again.Then, uncovering which third-party libraries were problematic, I activated those third-party libraries one by one. I found which third party libraries broke my project.
There were 4 third party libraries that broke my project : StickySwitch, ProgressView, SequenceLayout and Flashbar. When I removed those libraries, everything worked right. After removed the libraries, my Gradle file was as below.
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
android {
compileSdkVersion 29
buildToolsVersion "29.0.2"
defaultConfig {
applicationId "com.lotusif.dump2"
minSdkVersion 21
targetSdkVersion 29
versionCode 1
versionName "1.0"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility = 1.8
targetCompatibility = 1.8
}
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'androidx.appcompat:appcompat:1.1.0'
implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
implementation 'androidx.recyclerview:recyclerview:1.1.0'
implementation 'androidx.core:core:1.1.0'
// material widgets
implementation 'com.google.android.material:material:1.2.0-alpha03'
// progress bar with text BUGGY!
// implementation "com.github.skydoves:progressview:1.0.3"
// sequence progress BUGGY !
// implementation 'com.github.transferwise:sequence-layout:1.0.11'
// flash bar BUGGY !
// implementation 'com.andrognito.flashbar:flashbar:1.0.2'
// toggle - switch button BUGGY !
// implementation 'com.github.GwonHyeok:StickySwitch:0.0.15'
// Custom Toast message
implementation 'com.github.GrenderG:Toasty:1.4.2'
// liquid effect bar
implementation 'com.mikhaellopez:circularfillableloaders:1.3.2'
// bubble tab bar
implementation 'com.fxn769:bubbletabbar:1.0.3'
// android chart library
implementation 'com.github.PhilJay:MPAndroidChart:v3.1.0'
//glide image library
implementation 'com.github.bumptech.glide:glide:4.10.0'
annotationProcessor 'com.github.bumptech.glide:compiler:4.10.0'
// scaling layout
implementation 'com.github.iammert:ScalingLayout:1.2.1'
// lottie animation
implementation 'com.airbnb.android:lottie:3.3.1'
//Gson
implementation 'com.google.code.gson:gson:2.8.6'
//RxJava
implementation 'io.reactivex.rxjava2:rxjava:2.2.15'
implementation 'io.reactivex.rxjava2:rxandroid:2.0.1'
implementation 'com.daimajia.easing:library:2.1#aar'
implementation 'com.daimajia.androidanimations:library:2.3#aar'
//retrofit
implementation 'com.squareup.retrofit2:converter-gson:2.7.1'
implementation 'com.squareup.retrofit2:retrofit:2.7.1'
implementation 'com.squareup.retrofit2:adapter-rxjava2:2.7.1'
}
So, what was the common feature of those libraries that corrupt my project? My project was written with Java but that libraries were written with Kotlin. One second, cannot I use Kotlin libraries in my Java project? Yes, I can. I have to add android.useAndroidX=true and android.enableJetifier=true in my gradle.properties, that is it. But what if I have already added those lines in my gradle.properties and it has not worked?
# Specifies the JVM arguments used for the daemon process.
# The setting is particularly useful for tweaking memory settings.
org.gradle.jvmargs=-Xmx1536m
# When configured, Gradle will run in incubating parallel mode.
# This option should only be used with decoupled projects. More details, visit
# http://www.gradle.org/docs/current/userguide/multi_project_builds.html#sec:decoupled_projects
# org.gradle.parallel=true
# AndroidX package structure to make it clearer which packages are bundled with the
# Android operating system, and which are packaged with your app's APK
# https://developer.android.com/topic/libraries/support-library/androidx-rn
android.useAndroidX=true
# Automatically convert third-party libraries to use AndroidX
android.enableJetifier=true
I have not understood why kotlin libraries cannot work with my Java project. As you can see in my Gradle file, I am using apply plugin: 'kotlin-android' and apply plugin: 'kotlin-android-extensions' for Kotlin support.
How I have rescued my project? There were 2 available options as I knew. While first method was that to removed those 4 third party libraries and could not use them, second one that to convert all Java classes to Kotlin classes (I tried it before but it did not work until disabled all third party libraries). I chose to convert all Java classes to Kotlin classes. Thus, I was able to use 4 third party libraries which were mentioned above.
It took me 30 days to solve this problem. Now, I am working on Kotlin language. As a result, my project is running without any problem.

Error: Deprecated Gradle features were used in this build, making it incompatible with Gradle 6.0 [duplicate]

My android app Gradle build is not syncing, since I updated my android studio to 3.2. I have updated everything in the dependencies and still getting the same error. Here are the dependency files that I use ( Including third-party libraries)
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
android {
compileSdkVersion 28
defaultConfig {
applicationId "myappid"
minSdkVersion 19
targetSdkVersion 28
versionCode 32
versionName "3.2"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled true
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
debug {
minifyEnabled true
proguardFiles getDefaultProguardFile('proguard-android.txt'),
'proguard-rules.pro'
}
}
}
dependencies {
implementation fileTree(include: ['*.jar'], dir: 'libs')
implementation "org.jetbrains.kotlin:kotlin-stdlib:1.3.11"
implementation 'com.android.support:appcompat-v7:28.0.0-alpha1'
implementation 'com.android.support:design:28.0.0-alpha1'
implementation 'com.android.support:recyclerview-v7:28.0.0-alpha1'
implementation 'com.android.support:cardview-v7:28.0.0-alpha1'
implementation 'com.android.support:support-v4:28.0.0-alpha1'
implementation 'com.android.support.constraint:constraint-layout:1.1.3'
implementation 'com.google.firebase:firebase-crash:28.0.0-alpha1'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.2'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
implementation "org.jetbrains.anko:anko:$anko_version"
implementation 'com.github.GrenderG:Toasty:1.2.5'
implementation 'com.github.scottyab:showhidepasswordedittext:0.8'
implementation 'com.daimajia.easing:library:2.1#aar'
implementation 'com.daimajia.androidanimations:library:2.3#aar'
implementation 'com.google.android.gms:play-services-ads:17.1.2'
implementation 'com.google.gms:google-services:4.2.0'
implementation 'com.github.sd6352051:NiftyDialogEffects:v1.0.3'
implementation 'net.steamcrafted:load-toast:1.0.12'
implementation 'com.android.support:animated-vector-drawable:28.0.0-alpha1';
}
//apply plugin: 'com.google.gms.google-services'
//classpath 'com.google.gms:google-services:4.2.0'
However, I am getting the following error
Deprecated Gradle features were used in this build, making it incompatible with Gradle 5.0.
Use '--warning-mode all' to show the individual deprecation warnings.
I have tried most things available through Google/Youtube searches. Implemented few answers given in StackOverflow too. But at the end of the day, it's the same error. What I am missing.
Please advice, how to resolve the issue. Thank you
So the problem doesn't necessarily needs to be in your application level build.gradle script (the one you posted). It can also be in the project level one or even in the maven-publish-aar.gradle one (if you have it). This means, you could be using deprecated Gradle features on any Gradle script.
I have updated everything in the dependencies and still getting the same error.
Most likely, the warning will be gone once you identify and replace any deprecated Gradle feature that's causing you this trouble. To do this, it will help you to actually add the mentioned --warning-mode=all flag to your Gradle command line options (on your Android studio compiler settings):
This will print the proper warnings for you to be aware of what are the specific deprecated features your app is using.
In my case (for example), I just added the enableFeaturePreview('STABLE_PUBLISHING') setting on the settings.gradle file and that did the magic (I'm using publishing{}).
Also, I know you asked this near a month ago, but, it might be useful for other people facing the same issue.
Had same issue yesterday extended to the #Hugo Allexis Cardona answer even after replacing deprecated Gradle feature having same issue because Old build folder is remains there so what I did is Remove app/build folder and sync gradle again and it work for me Thanks #Hugo Allexis Cardona
Delete App/Build Folder
The Problem is because of the inconsistency of external dependencies.
The Issue can be Easily Solved by migrating to Yarn Package Manager
Delete Node Modules
Delete Package.json.lock
yarn install
OR
Try Deleting android/app/build folder
The run the project by react-native run-android
I found easiest way to solve this issue. Go to projectName/android directory and in terminal enter the following command
./gradlew clean
And then, go to main project directory by entering following command
cd ..
And then start the project
react-native run-android
In my case
I Followed Hugo's answer
Changed the location of project.
Tried another android device [Build and success install]
Tried on my android device [Build and success install]

Deprecated Gradle features making it incompatible with Gradle 5.0. Android Studio 3.2

My android app Gradle build is not syncing, since I updated my android studio to 3.2. I have updated everything in the dependencies and still getting the same error. Here are the dependency files that I use ( Including third-party libraries)
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
android {
compileSdkVersion 28
defaultConfig {
applicationId "myappid"
minSdkVersion 19
targetSdkVersion 28
versionCode 32
versionName "3.2"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled true
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
debug {
minifyEnabled true
proguardFiles getDefaultProguardFile('proguard-android.txt'),
'proguard-rules.pro'
}
}
}
dependencies {
implementation fileTree(include: ['*.jar'], dir: 'libs')
implementation "org.jetbrains.kotlin:kotlin-stdlib:1.3.11"
implementation 'com.android.support:appcompat-v7:28.0.0-alpha1'
implementation 'com.android.support:design:28.0.0-alpha1'
implementation 'com.android.support:recyclerview-v7:28.0.0-alpha1'
implementation 'com.android.support:cardview-v7:28.0.0-alpha1'
implementation 'com.android.support:support-v4:28.0.0-alpha1'
implementation 'com.android.support.constraint:constraint-layout:1.1.3'
implementation 'com.google.firebase:firebase-crash:28.0.0-alpha1'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.2'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
implementation "org.jetbrains.anko:anko:$anko_version"
implementation 'com.github.GrenderG:Toasty:1.2.5'
implementation 'com.github.scottyab:showhidepasswordedittext:0.8'
implementation 'com.daimajia.easing:library:2.1#aar'
implementation 'com.daimajia.androidanimations:library:2.3#aar'
implementation 'com.google.android.gms:play-services-ads:17.1.2'
implementation 'com.google.gms:google-services:4.2.0'
implementation 'com.github.sd6352051:NiftyDialogEffects:v1.0.3'
implementation 'net.steamcrafted:load-toast:1.0.12'
implementation 'com.android.support:animated-vector-drawable:28.0.0-alpha1';
}
//apply plugin: 'com.google.gms.google-services'
//classpath 'com.google.gms:google-services:4.2.0'
However, I am getting the following error
Deprecated Gradle features were used in this build, making it incompatible with Gradle 5.0.
Use '--warning-mode all' to show the individual deprecation warnings.
I have tried most things available through Google/Youtube searches. Implemented few answers given in StackOverflow too. But at the end of the day, it's the same error. What I am missing.
Please advice, how to resolve the issue. Thank you
So the problem doesn't necessarily needs to be in your application level build.gradle script (the one you posted). It can also be in the project level one or even in the maven-publish-aar.gradle one (if you have it). This means, you could be using deprecated Gradle features on any Gradle script.
I have updated everything in the dependencies and still getting the same error.
Most likely, the warning will be gone once you identify and replace any deprecated Gradle feature that's causing you this trouble. To do this, it will help you to actually add the mentioned --warning-mode=all flag to your Gradle command line options (on your Android studio compiler settings):
This will print the proper warnings for you to be aware of what are the specific deprecated features your app is using.
In my case (for example), I just added the enableFeaturePreview('STABLE_PUBLISHING') setting on the settings.gradle file and that did the magic (I'm using publishing{}).
Also, I know you asked this near a month ago, but, it might be useful for other people facing the same issue.
Had same issue yesterday extended to the #Hugo Allexis Cardona answer even after replacing deprecated Gradle feature having same issue because Old build folder is remains there so what I did is Remove app/build folder and sync gradle again and it work for me Thanks #Hugo Allexis Cardona
Delete App/Build Folder
The Problem is because of the inconsistency of external dependencies.
The Issue can be Easily Solved by migrating to Yarn Package Manager
Delete Node Modules
Delete Package.json.lock
yarn install
OR
Try Deleting android/app/build folder
The run the project by react-native run-android
I found easiest way to solve this issue. Go to projectName/android directory and in terminal enter the following command
./gradlew clean
And then, go to main project directory by entering following command
cd ..
And then start the project
react-native run-android
In my case
I Followed Hugo's answer
Changed the location of project.
Tried another android device [Build and success install]
Tried on my android device [Build and success install]

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.

Jacoco Code Coverage in android studio

I am trying to generate Jacoco code coverage report.
I have used AndroidTestCase for my test classes.
I have found using testCoverageEnabled true and using default android -studio default jacoco,
./gradlew connectedCheck or createDebugCoverageReport
create the percentage of successfull/fail test cases, but no coverage report.
Then I have tried jacoco {toolVersion "0.7.1.201405082137"}, and task jacocoTestReport(type:JacocoReport, dependsOn: "testDebug"). I have tried to change the dependsOn value with various task. The report shows 0 (zero) test coverage, which is impossible because at least half of all classes are tested.
I have followed various accepted answer of stack overflow in last couple of days. The result is negative.
My gradle file:
buildscript {
repositories {
mavenLocal()
mavenCentral()
}
dependencies {
classpath 'com.android.tools.build:gradle:1.0.0'
}
}
apply plugin: 'com.android.application'
apply plugin: 'jacoco'
android {
compileSdkVersion 21
buildToolsVersion "21.1.2"
defaultConfig {
applicationId "test.gradle.com.myapplicationtestgradle"
minSdkVersion 21
targetSdkVersion 21
versionCode 1
versionName "1.0"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile(
'proguard-android.txt'), 'proguard-rules.pro'
}
debug {
testCoverageEnabled true
}
}
jacoco {
version "0.7.1.201405082137"
}
packagingOptions {
exclude 'LICENSE.txt'
}
}
jacoco {
toolVersion "0.7.1.201405082137"
}
task jacocoTestReport(type:JacocoReport, dependsOn: "testDebug") {
group = "Reporting"
description = "Generate Jacoco coverage reports"
// exclude auto-generated classes and tests
def fileFilter = ['**/R.class', '**/R$*.class',
'**/BuildConfig.*', '**/Manifest*.*',
'android/**/*.*']
def debugTree = fileTree(dir:
"${project.buildDir}/intermediates/classes/debug",
excludes: fileFilter)
def mainSrc = "${project.projectDir}/src/main/java"
sourceDirectories = files([mainSrc])
classDirectories = files([debugTree])
additionalSourceDirs = files([
"${buildDir}/generated/source/buildConfig/debug",
"${buildDir}/generated/source/r/debug"
])
executionData = fileTree(dir: project.projectDir, includes:
['**/*.exec', '**/*.ec'])
reports {
xml.enabled = true
xml.destination = "${buildDir}/jacocoTestReport.xml"
csv.enabled = false
html.enabled = true
html.destination = "${buildDir}/reports/jacoco"
}
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
androidTestCompile('junit:junit:4.11') {
exclude module: 'hamcrest-core'
}
}
Gradle already has built-in support for generating test coverage reports and we don't need to create any additional configurations or add any plugins to generate test coverage report. Basically, the only thing we need to do is to set testCoverageEnabled parameter to true in build.gradle file as follows:
android {
buildTypes {
debug {
testCoverageEnabled = true
}
}
}
Next, we can execute the following Gradle task from CLI:
./gradlew createDebugCoverageReport
On Windows, we can execute it like this:
gradlew.bat createDebugCoverageReport
Task will analyze code of our project in /src/main/java/ directory and unit tests placed in /src/androidTest/java/ directory.
After executing this task, we can find test coverage report in the following directory of the module:
/build/outputs/reports/coverage/debug/
When we open index.html file, we can see a visual report from test coverage, which can be viewed in a web browser.
It looks as on the image below.
I've written an article about test coverage report in Android application and published it on my blog some time ago. If you are interested in that topic, you can read it at:
https://web.archive.org/web/20171210224809/http://blog.wittchen.biz.pl/test-coverage-report-for-android-application (Old blog, with user comments)
http://wittchen.io/test-coverage-in-android-applications/ (New blog, without user comments)
Update (Unit test coverage for Robolectric tests)
If you would like to create test coverage report from unit tests written with Robolectric and generate test coverage report with Jacoco, Travis CI and Codecov.io, please take a look at the new article on my blog:
https://web.archive.org/web/20171013015925/http://blog.wittchen.biz.pl/test-coverage-report-with-travis-ci-for-robolectric-tests-on-android/ (Old blog)
http://wittchen.io/unit-test-coverage-report-with-travis-ci-for-robolectric-on-android/ (New blog, without user comments)
I see that you already got it working, however, there's a simpler method for getting Unit Test execution data. I recently was looking into this as well, I actually made a full write up earlier today.
In my situation, I didn't want to create an additional Gradle task as I wanted the report to be generated as a part of the existing workflow. I also didn't want to explicitly add the Jacoco plugin, as Google already dups the Jacoco Ant tasks for the coverage reports for Instrumentation Tests.
In addition to setting the properties android.jacoco.version and buildTypes.debug.testCoverageEnabled, I added the following to the testDebug JVM arguments to generate execution data:
project.afterEvaluate {
def append = "append=true"
def destFile = "destfile=$buildDir/outputs/code-coverage/connected/coverage.ec"
testDebug.jvmArgs "-javaagent:$buildDir/intermediates/jacoco/jacocoagent.jar=$append,$destFile"
createDebugCoverageReport.dependsOn testDebug
}
This appends the Unit Test execution data to the coverage file generated by connectedAndroidTest, so your report reflects both Instrumentation Tests and Unit Tests, rather than each variant individually.
Note that connectedAndroidTest overwrites the coverage file, take this into account when creating your report. If the task testDebug doesn't have any changes, and you run createDebugCoverageReport, it will only reflect your Instrumentation Test coverage. So, make a change to your Unit Tests. The Linux command touch may be useful here, although I haven't tried yet.
Today I did completely removed android studio, android sdk, gradle. Then reinstall everything. After that, I just added inside the app build.gradle.
debug {
testCoverageEnabled true
}
Then I run ./gradlew connectedChec. Everything is working perfectly. Android studio default Jacoco working fine for me. I think it is also possible to create a jacocoTestReport Task and then create code coverage.I don't know why gradle and android studio was not working previously.
i investigated correct way to get merged code coverage report with Jacoco, you can check it here: https://gist.github.com/ultraon/54cca81ca159ed0a4a9ebf62e89c26ba
I used AndroidStudio 2.2.2 with Gradle 3.2 and Android Gradle Plugin 2.2.2
I had the same problem too, but I made a mistake in the process which took a few days to track down. Here's my technique and the gotcha that caused the 0% coverage.
Install jacoco. I used the technique described in great detail here with a few modifications because of my project's structure. Thank you Ashish Uniyal!
Run jacoco. Open the Gradle window in Android Studio (View -> Tool Windows -> Gradle), click on the elephant icon to "Execute Gradle Task."
If a pop-up to your settings occurs, go ahead and disable the "Do not build Gradle task list during Gradle sync."
In the text window that pops up after clicking the elephant icon, type in: gradle app:createDebugUnitTestCoverageReport and hit [Enter].
If you want to do AndroidTests, type gradle app:createDebugAndroidTestCoverageReport.
It'll take several seconds to a few minutes to execute jacoco.
Find the results. This can vary depending on your settings in the jacoco.gradle file. But generally you can find the results an index.html file here: ./app/build/reports/coverage/test/debug/index.html.
My big gotcha was that I typed in the AndroidTest instead of the UnitTest (thank you auto-complete, sigh). Since I only did unit testing all jacoco could see was a big fat 0%.

Categories

Resources