Instrumented Tests in Android Studio - android

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.

Related

Android studio code coverage not showing any Kotlin classes

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.

Can't run unit tests in Android Studio

I'm trying to make my unit tests work again for two days now, every time that I try to run them I get this error:
Process finished with exit code 1
Class not found: "XXXXX.XXXXX.XXXXX.XXX"Empty test suite.
This happens trying to run both the test class, or just the methods. I've tried to clean all the test configurations and rebuild the project. Furthermore, I was able to find other people having the same problem, therefore, the proposed solutions were not effective to fix my issue.
This is my gradle file:
apply plugin: 'com.android.application'
android {
compileSdkVersion 25
buildToolsVersion '25.0.1'
defaultConfig {
applicationId "XXXXXXXXXX"
minSdkVersion 19
targetSdkVersion 25
versionCode 1
versionName "1.0.0"
multiDexEnabled true
}
buildTypes {
debug {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
release {
minifyEnabled true
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
dataBinding {
enabled = true
}
}
buildscript {
repositories {
maven { url 'https://maven.fabric.io/public' }
}
dependencies {
// The Fabric Gradle plugin uses an open ended version to react
// quickly to Android tooling updates
classpath 'io.fabric.tools:gradle:1.+'
}
}
buildscript {
repositories {
mavenCentral()
}
dependencies {
classpath 'me.tatarka:gradle-retrolambda:3.4.0'
}
}
apply plugin: 'io.fabric'
apply plugin: 'me.tatarka.retrolambda'
ext {
supportLibVersion = '25.1.0' // variable that can be referenced to keep support libs consistent
jomlVersion = '1.8.4'
}
repositories {
jcenter()
maven { url 'https://maven.fabric.io/public' }
}
dependencies {
compile fileTree(include: ['*.jar'], dir: 'libs')
testCompile 'junit:junit:4.12'
compile "com.android.support:appcompat-v7:${supportLibVersion}"
compile "com.android.support:design:${supportLibVersion}"
compile "com.android.support:recyclerview-v7:${supportLibVersion}"
compile "com.android.support:cardview-v7:${supportLibVersion}"
compile "com.android.support:support-v4:${supportLibVersion}"
compile('com.crashlytics.sdk.android:crashlytics:2.6.5#aar')
{
transitive = true;
}
compile project(':circular-slider')
compile project(':gpuimage-plus')
compile 'de.hdodenhof:circleimageview:2.1.0'
compile 'net.protyposis.android.mediaplayer:mediaplayer:4.2.2-rc1'
compile 'net.protyposis.android.mediaplayer:mediaplayer-dash:4.2.2-rc1'
compile 'com.google.code.gson:gson:2.7'
compile 'com.squareup.retrofit2:retrofit:2.1.0'
compile 'com.squareup.retrofit2:converter-gson:2.1.0'
compile 'com.writingminds:FFmpegAndroid:0.3.2'
compile 'com.makeramen:roundedimageview:2.3.0'
compile 'io.reactivex:rxjava:1.2.4'
compile 'io.reactivex:rxandroid:1.2.1'
compile 'com.minimize.android:rxrecycler-adapter:1.2.2'
compile "org.joml:joml:${jomlVersion}"
provided 'org.glassfish:javax.annotation:10.0-b28'
compile 'org.jetbrains:annotations-java5:15.0'
compile 'com.annimon:stream:1.1.3'
testCompile 'org.mockito:mockito-core:1.10.19'
testCompile 'org.powermock:powermock-api-mockito:1.6.5'
testCompile 'org.powermock:powermock-module-junit4-rule-agent:1.6.5'
testCompile 'org.powermock:powermock-module-junit4-rule:1.6.5'
testCompile 'org.powermock:powermock-module-junit5:1.6.5'
compile 'com.google.android.gms:play-services-appindexing:8.4.0'
compile 'com.android.support:multidex:1.0.1'
}
And the beginning of the class with the tests:
#PrepareForTest({XXXXXX.class, XXXXXX.class, XXXXXX.class, XXXXXX.class})
#RunWith(PowerMockRunner.class)
public class VideoPlayerModelUnitTest {
Thanks!
Update
I was able to fix partially the problem by changing the references in my AndroidMaifest file.
Therefore, changing the references from:
<activity android:name="com.myapp.MusicSelector.MusicSelectorActivity"/>
To:
<activity android:name=".MusicSelector.MusicSelectorActivity"/>
However, I can't create new tests or even rename my tests methods. For example, if I rename from:
#Test
public void testVideoListToTimedClips() throws Exception {
to:
#Test
public void testVideoListToTimedClips2() throws Exception {
I get the error:
java.lang.Exception: No tests found matching Method testVideoListToTimedClips2(io.collect.collect.functional.VideoPlayerModelIntegrationTest) from org.junit.internal.requests.ClassRequest#15eb5ee5
Update 2
Trying things out, seems like Android Studio is keeping the reference to the an old version of the tests.
I changed the name of the test method from testVideoListToTimedClips to testVideoListToTimedClips2 resulting in a test class like that:
#PrepareForTest({VideoPlayerModel.class, MediaPlayer.class, Common.class})
#RunWith(PowerMockRunner.class)
public class testVideoPlayerModelIntegration {
#Test
public void testVideoListToTimedClips2() throws Exception {
And when I run the test class, Android Studio runs the old method:
Are you using Android Studio 2.3.0-beta1? If so, there's a bug that causes your unit tests to not get built when you try to run them.
You can work around the issue by first running Make project and then Run each time you want to run the unit tests.
This issue is supposed to be fixed in the next canary/beta version of Android studio.
Source:
https://code.google.com/p/android/issues/detail?id=230688
I was facing similar type of issue.
I was building using following command :
gradle clean build -x test
This skips the test cases.
instead try : gradle clean build
Clean your project in IDE. This will load latest class file and refresh its references.
I had similar issue. You need to check whether the issue is in the code or android studio. try run unit test using command prompt / terminal
./gradlew testDevelopDebugUnitTest
DevelopDebug is flavour that I have in the code so it might be different with yours. If that command is executed successfully then the issue is in android studio.
Once I run this command manually then the issue fix itself ( I'm not sure the reason though ). Hopefully can help you guys. Thank you
I was able to fix the problem by changing the references in the Manifest file from:
<activity android:name="com.myapp.MusicSelector.MusicSelectorActivity"/>
To:
<activity android:name=".MusicSelector.MusicSelectorActivity"/>
Also, after every change on the tests I need to make my project manually.
At some point you should declare your test runner in the module gradle config. For example inside defaultConfig:
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
Right click on the class which you want to test and click run.

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.

Dagger not generating components for /test class

I am following the guide here: https://github.com/ecgreb/dagger-2-testing-demo
I have the following setup in my app/src/main (the injection and #Provides code omitted):
public class FlingyApplication extends Application {
#Singleton
#Component(modules = { FlingyModule.class })
public interface FlingyComponent
}
#Module
public class FlingyModule
In app/src/test:
public class TestFlingyApplication extends Application {
#Singleton
#Component(modules = { TestFlingyModule.class })
public interface TestFlingyComponent extends FlingyComponent
}
#Module
public class TestFlingyModule
So far, it is nearly identical to the example github. When dagger goes to generate the code for the Component builders in src/main, they generate properly. Dagger does not, however, generate code for the Component builders in src/test.
My main build.gradle:
dependencies {
classpath 'com.android.tools.build:gradle:2.1.0-alpha3'
classpath 'com.neenbedankt.gradle.plugins:android-apt:1.5.1'
}
My app/build.gradle
apply plugin: 'com.android.application'
apply plugin: 'com.neenbedankt.android-apt'
android {
# There is obviously more in here, but this is the custom part:
packagingOptions {
exclude 'META-INF/services/javax.annotation.processing.Processor'
}
}
dependencies {
compile 'com.squareup:otto:1.3.8'
compile 'com.android.support:cardview-v7:23.1.1'
compile 'com.android.support:recyclerview-v7:23.1.1'
compile 'com.android.support:appcompat-v7:23.1.1'
compile 'com.android.support:design:23.1.1'
compile 'com.squareup.picasso:picasso:2.5.2'
compile 'com.jakewharton:butterknife:7.0.1'
compile 'com.google.dagger:dagger:2.0.1'
apt 'com.google.dagger:dagger-compiler:2.0.1'
compile 'javax.annotation:javax.annotation-api:1.2'
compile 'io.reactivex:rxandroid:1.1.0'
compile 'io.reactivex:rxjava:1.1.0'
testCompile 'com.neenbedankt.gradle.plugins:android-apt:1.4'
testCompile 'junit:junit:4.12'
testCompile 'org.robolectric:robolectric:3.0'
testCompile 'org.mockito:mockito-core:1.10.19'
}
So when I build, I get the DaggerFlingyApplication_FlingyComponent class, but not the DaggerTestFlingyApplication_TestFlingyComponent
Something interesting I noticed is that if I switch the line:
apt 'com.google.dagger:dagger-compiler:2.0.1'
# TO
compile 'com.google.dagger:dagger-compiler:2.0.1'
I see the following when I run ./gradlew compileDebugUnitTestSources:
:app:compileDebugJavaWithJavac
Note: /app/build/generated/source/apt/debug/com/jy/flingy/DaggerFlingyApplication_FlingyComponent.java uses unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.
:app:preDebugUnitTestBuild UP-TO-DATE
:app:prepareDebugUnitTestDependencies
:app:compileDebugUnitTestJavaWithJavac
Note: /app/build/intermediates/classes/test/debug/com/jy/flingy/DaggerTestFlingyApplication_TestFlingyComponent.java uses unchecked or unsafe operations.
I don't know why it builds to intermediates and I assume that I need the build.gradle file to use apt instead of compile, but I can't seem to figure out how to get this to work. I know that it's absolutely possible.
You need to add following to your build.gradle file for instrumentation test:
androidTestApt 'com.google.dagger:dagger-compiler:<version>'
or for JUnit test:
testApt 'com.google.dagger:dagger-compiler:<version>'
This is required to generate Dagger code for your test components.
EDIT:
If you are using jack tool chain then add following
for android test:
androidTestAnnotationProcessor 'com.google.dagger:dagger-compiler:<version>'
for JUnit tests:
testAnnotationProcessor 'com.google.dagger:dagger-compiler:<version>'
EDIT:
In case you are using kotlin-kapt for Kotlin code use following:
kaptAndroidTest 'com.google.dagger:dagger-compiler:<version>'
or for JUnit test:
kaptTest 'com.google.dagger:dagger-compiler:<version>'
Check this link for more info.
For Android Studio 3 and dagger 2.13 the already mentioned annotation processors are needed:
testAnnotationProcessor 'com.google.dagger:dagger-compiler:2.13'
But also do not forgot to do this for the instrumented test under androidTest:
androidTestAnnotationProcessor'com.google.dagger:dagger-compiler:2.13'
You might get the impression that this alone does not work, because the DaggerXYZ classes are not generated. After hours I found out that the test source generation is only triggered when the tests are executed. If you start a test or androidTest from Android Studio the source generation should be triggered.
If you need this earlier trigger gradle manually:
gradlew <moduledirectory>:compile<Flavor>DebugAndroidTestSources
gradlew <moduledirectory>:compile<Flavor>DebugTestSources
Replace Debug if you run a test in a different build type.
Note:
If you are using multiDexEnable = true you might get an error:
Test running failed: Instrumentation run failed due to
'java.lang.IncompatibleClassChangeError'
Use a different runner in this case:
android {
defaultConfig {
multiDexEnabled true
testInstrumentationRunner "com.android.test.runner.MultiDexTestRunner"
Just to add a bit to the above answer, since there have been some recent changes.
From Android Gradle plugin version 2.2 and above you will no longer use testApt.
So from now on you need to put only this in the build.gradle:
testAnnotationProcessor 'com.google.dagger:dagger-compiler:<version>'
But more than that, what I came here for, is the following: if you need gradle to generate the DaggerComponent classes for you you will have to do a bit extra work.
Open our build.gradle file and AFTER the android section write this:
android.applicationVariants.all { variant ->
if (variant.buildType.name == "debug") {
def aptOutputDir = new File(buildDir, "generated/source/apt/${variant.unitTestVariant.dirName}")
variant.unitTestVariant.addJavaSourceFoldersToModel(aptOutputDir)
assembleDebug.finalizedBy('assembleDebugUnitTest')
}
}
This will create the directory build/generated/source/apt/test/ as a Java classes recipient and the last part will trigger the "assembleDebugUnitTest" task that will finally create those Dagger2 components in the folder that was just created.
Note that this script is just being triggered for the "debug" variant and takes advantage of that build variant using the "assembleDebug" task. If for some reason you need it in other variants just tweak that a bit.
Why Dagger2 does not do this automatically is beyond me, but hey, I am no pro.
If you added kaptAndroidTest for dagger dependencies and still not getting test components when rebuild your project, try running assembleAndroidTest.
Adding to the above solution and adding the testKapt and androidTestKapt for dagger, I had the problem that my modules and components had the wrong imports as a result of missing imports
e.g
import android.support.test.espresso.core.deps.dagger.Module
import android.support.test.espresso.core.deps.dagger.Module
instead of
import dagger.Module
import dagger.Provides
Hope this helps
Hi even after adding all gradle dependenices and annotations if it still doesnt work then you need to run assembleAndroidTest gradle script for this.
Simply make an empty test case and run it. It will do the job for you.
Cheers
If you are using kotlin use "kaptAndroidTest" to generate dagger component for android tests in your build.gradle file.
I ran ./gradlew build from the command line and got information about a missing Provides method that Android Studio was not telling me about.

junit testing with gradle for an android project

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.

Categories

Resources