java.lang.IllegalStateException: Could not initialize plugin: MockMaker - android

Trying to run instrumentation test on AS.
stuck with this Error:
java.lang.IllegalStateException: Could not initialize plugin: interface org.mockito.plugins.MockMaker
at org.mockito.internal.configuration.plugins.PluginLoader$1.invoke(PluginLoader.java:66)
at java.lang.reflect.Proxy.invoke(Proxy.java:393)
at $Proxy4.isTypeMockable(Unknown Source)
ExampleInstrumentedTest.java
#RunWith(AndroidJUnit4.class)
public class ExampleInstrumentedTest {
#Mock
Context context;
#Before
public void init(){
MockitoAnnotations.initMocks(this);
}
#Test
public void testDisabledFlag() {
ChanceValidator chanceValidator = new ChanceValidator(context);
Validator.ValidationResult result = chanceValidator.validate(2);
assertEquals(result, Validator.ValidationResult.NO_ERROR);
}
}
build.gradle
apply plugin: 'com.android.application'
android{
..
defaultConfig {
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
testOptions {
unitTests.returnDefaultValues = true
}
}
dependencies {
compile fileTree(include: ['*.jar'], dir: 'libs')
// Unit testing dependencies
testCompile 'junit:junit:4.12'
// Set this dependency if you want to use the Hamcrest matcher library
testCompile 'org.hamcrest:hamcrest-library:1.3'
// more stuff, e.g., Mockito
androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
exclude group: 'com.android.support', module: 'support-annotations'
})
compile 'com.android.support:appcompat-v7:25.1.0'
compile project(':mortar')
compile project(':mockito-core-2.6.6')
}
Update:
After commenting line-
MockitoAnnotations.initMocks(this);
It is building fine(No Exception) but context mocked is now null.

This Worked in my case:
dependencies {
def mockito_version = '2.7.1' // For local unit tests on your development machine
testCompile "org.mockito:mockito-core:$mockito_version" // For instrumentation tests on Android devices and emulators
androidTestCompile "org.mockito:mockito-android:$mockito_version"
}
I didn’t comment initMocks

In my case, I was working on a project that does not use the maven build system. So this is what worked for me.
Navigated to the maven repo for mockito (used v2.26): https://mvnrepository.com/artifact/org.mockito/mockito-core/2.26.0. I downloaded the jar.
On the same page at the bottom, I looked up the dependencies. For mockito 2.26.0, these dependencies are:
Byte Buddy v.1.9.10
(https://mvnrepository.com/artifact/net.bytebuddy/byte-buddy/1.9.10)
Byte Buddy Java Agent v1.9.10
(https://mvnrepository.com/artifact/net.bytebuddy/byte-buddy-agent/1.9.10)
Objenesis v2.6
(https://mvnrepository.com/artifact/org.objenesis/objenesis/2.6) I
downloaded the jar files for the above mockito dependencies.
In Eclipse I created a user library containing the four jar file and added it to my project.
NB: (creating the library is optional, you can add the jars directly to your project build path)
Hope this helps someone.

Do not explicitly include mockito, let powermock pull in what it needs.

I got this problem resolved after adding transitive dependencies for 'mockito-core'.
I was facing this problem in eclipse. I was using 'mockito-core 3.8.0' along with 'mockito-junit-jupiter 3.8.0'.
At first I tried to resolve this by changing JRE to JDK in Project/ Java Build Path ((as many have posted this as resolution), but that did not solve the problem.
Then I added below 3 transitive dependencies for 'mockito-core 3.8.0' explicitly, and it worked!
1. net.bytebuddy » byte-buddy v1.10.20
2. net.bytebuddy » byte-buddy-agent v1.10.20
3. org.objenesis » objenesis v3.1
(https://mvnrepository.com/artifact/org.mockito/mockito-core/3.8.0 - see compiled dependencies)

I am using Quarkus on a big project with many people.
Most of our microservices used this dependency version
<net.bytebuddy.version>1.12.9</net.bytebuddy.version>
One microservice used:
<net.bytebuddy.version>1.11.0</net.bytebuddy.version>
Which was not compatible with our
<artifactId>quarkus-junit5-mockito</artifactId>
When I added more tests on a resource, I got the error of this question.
I changed the bytebuddy to 1.12.9 and mockito worked.
Make sure your bytebyddy's version is compatible with you mockito version.
Updated either one of them to be compatible with each other.

Related

Class module-info is missing a super type

I am trying to build an android application with some dependencies however one of them is causing this error:
Illegal class file: Class module-info is missing a super type.
The dependency causing the issue is JOML a math library for use with OpenGL.
The dependency is included as
dependencies {
implementation fileTree(include: '*.jar', dir: 'libs')
implementation 'org.joml:joml:1.9.9'
...
}
I am using android studio/gradle version 3.1 and build tools version 27.0.3.
I have tried clean and rebuild and clearing Android Studio cashes.
Another thing to note is that it was compiling fine the other day even with this dependency.
You should use JOML for Android instead of the Java version.
Application build.gradle
buildscript {
repositories {
maven {
url "https://oss.sonatype.org/content/repositories/snapshots/"
}
...
}
...
}
App build.gradle
dependencies {
implementation "org.joml:joml-android:1.9.3-SNAPSHOT"
}

Using Dagger 2.11 with kotlin in android [duplicate]

I created a new project in Android Studio 2.2 Preview 1 with Android App and Backend module with Google Messaging. This is the app file:
apply plugin: 'com.android.application'
android {
compileSdkVersion 23
buildToolsVersion "23.0.3"
defaultConfig {
applicationId "com.xxx.xxx"
minSdkVersion 15
targetSdkVersion 23
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile 'com.android.support:appcompat-v7:23.4.0'
compile 'com.android.support.constraint:constraint-layout:1.0.0-alpha1'
compile 'com.google.android.gms:play-services-gcm:9.0.0'
testCompile 'junit:junit:4.12'
androidTestCompile 'com.android.support.test.espresso:espresso-core:2.2.2'
androidTestCompile 'com.android.support.test:runner:0.5'
androidTestCompile 'com.android.support:support-annotations:23.4.0'
compile project(path: ':backend', configuration: 'android-endpoints')
}
But it's giving:
Error:Conflict with dependency 'com.google.code.findbugs:jsr305'. Resolved versions for app (1.3.9) and test app (2.0.1) differ. See http://g.co/androidstudio/app-test-app-conflict for details.
I am new to Android and not able to find what is this error. How do I fix it?
In your app's build.gradle add the following:
android {
configurations.all {
resolutionStrategy.force 'com.google.code.findbugs:jsr305:1.3.9'
}
}
Enforces Gradle to only compile the version number you state for all dependencies, no matter which version number the dependencies have stated.
This is due to espresso. You can add the following to your apps build.grade to mitigate this.
androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2') {
exclude group: 'com.google.code.findbugs'
}
METHOD 1:
I deleted the androidTestCompile on espresso-core line which was automatically included in a new project. Then my Android Studio compiles clean.
The androidTestCompile is in "build.gradle (Module:app)":
dependencies {
...
androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
exclude group: 'com.android.support', module: 'support-annotations'
})
...
}
I don't know whether this deletion will have any problem down the road, but it surely works for my current project now.
METHOD 2: Adding an exclude on findbugs works too:
dependencies {
...
androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
exclude group: 'com.android.support', module: 'support-annotations'
exclude group: 'com.google.code.findbugs'
})
...
}
METHOD 3: Forcing compiling with a specific version:
(In the following I force it to compile with the higher version.)
dependencies {
...
androidTestCompile 'com.google.code.findbugs:jsr305:3.0.0'
...
}
From Gradle Plugin User Guide:
When instrumentation tests are run, both the main APK and test APK share the same classpath. Gradle build will fail if the main APK and the test APK use the same library (e.g. Guava) but in different versions. If gradle didn't catch that, your app could behave differently during tests and during normal run (including crashing in one of the cases).
To make the build succeed, just make sure both APKs use the same version. If the error is about an indirect dependency (a library you didn't mention in your build.gradle), just add a dependency for the newer version to the configuration
Add this line to your build.gradle dependencies to use newer version for both APKs:
compile('com.google.code.findbugs:jsr305:2.0.1')
For future reference, you can check your Gradle Console and it will provide a helpful link next to the error to help with any gradle build errors.
The reason why this happen is that diff dependency use same lib of diff version.
So, there are 3 steps or (1 step) to solve this problem.
1st
Add
configurations.all {
resolutionStrategy.force 'com.google.code.findbugs:jsr305:2.0.1'
}
to your build.gradle file in android {...}
2nd
Open terminal in android studio
run ./gradlew -q app:dependencies command.
3rd
Click Clean Project from menu bar of android studio in Build list.
It will rebuild the project, and then
remove code in 1st step.
Maybe you need just exec 2nd step. I can't rollback when error occurs.
Have a try.
When I added module: 'jsr305' as an additional exclude statement, it all worked out fine for me.
androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
exclude group: 'com.android.support', module: 'support-annotations'
exclude module: 'jsr305'
})
The problem, as stated in your logs, is 2 dependencies trying to use different versions of 3rd dependency.
Add one of the following to the app-gradle file:
androidTestCompile 'com.google.code.findbugs:jsr305:2.0.1'
androidTestCompile 'com.google.code.findbugs:jsr305:1.3.9'
The accepted answer is one way of fixing the issue, because it will just apply some strategy for the problematic dependency (com.google.code.findbugs:jsr305) and it will resolve the problem around the project, using some version of this dependency. Basically it will align the versions of this library inside the whole project.
There is an answer from #Santhosh (and couple of other people) who suggests to exclude the same dependency for espresso, which should work by the same way, but if the project has some other dependencies who depend on the same library (com.google.code.findbugs:jsr305), again we will have the same issue. So in order to use this approach you will need to exclude the same group from all project dependencies, who depend on com.google.code.findbugs:jsr305. I personally found that Espresso Contrib and Espresso Intents also use com.google.code.findbugs:jsr305.
I hope this thoughts will help somebody to realise what exactly is happening here and how things work (not just copy paste some code) :).
Add this this to dependencies to force using latest version of findbugs library:
compile 'com.google.code.findbugs:jsr305:2.0.1'
delete espresso dependencies in gradle file works for me.
delete those lines in app gradle file:
androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
exclude group: 'com.android.support', module: 'support-annotations'
})
i was trying to use airbnb deeplink dispatch and got this error. i had to also exlude the findbugs group from the annotationProcessor.
//airBnb
compile ('com.airbnb:deeplinkdispatch:3.1.1'){
exclude group:'com.google.code.findbugs'
}
annotationProcessor ('com.airbnb:deeplinkdispatch-processor:3.1.1'){
exclude group:'com.google.code.findbugs'
}
Those who are getting same error in Android 3.0.1,can resolve it by simply update the versions of compileSdkVersion and targetSdkVersion to 27 and also Implement com.android.support:appcompat-v7:27.1.1' in dependencies.
In project ':app' you can add the following to your app/build.gradle file :
android {
configurations.all {
resolutionStrategy.force 'com.google.code.findbugs:jsr305:1.3.9'
}
}
For react-native-firebase, adding this to app/build.gradle dependencies section made it work for me:
implementation('com.squareup.okhttp3:okhttp:3.12.1') { force = true }
implementation('com.squareup.okio:okio:1.15.0') { force = true }
implementation('com.google.code.findbugs:jsr305:3.0.2') { force = true}
REACT NATIVE
If you looking for react native solution, then write this snippet in your affected node_modules gradle build file, e.g. firebase in my case.
android {
configurations.all {
resolutionStrategy.force 'com.google.code.findbugs:jsr305:3.0.0'
}
}

what is the difference between compile, testCompile and provided in gradle dependency

I am using android studio and in project structure -> dependencies tab following options i can see:
Compile
Provided
APK
Test Compile
Debug Compile
Release Compile
my question: what is the difference between compile, testCompile and provided in gradle dependency
compile is the group of dependencies you need to build your application while testCompile is a group of dependencies that you need only for testing.
Look for instance at this build.gradle (taken from here)
apply plugin: 'java'
repositories {
mavenCentral()
}
dependencies {
compile group: 'org.hibernate', name: 'hibernate-core', version: '3.6.7.Final'
testCompile group: 'junit', name: 'junit', version: '4.+'
}
This specifies that hibernate-core is needed to build your code but junit (a testing framework) is needed just for testing. Since it's not needed at runtime, it's not going to be included in the released package.
You should read the User Guide that comes with the distribution, or read it online at http://gradle.org/documentation/ .
In short, "compile" is for dependencies for your "main" code, "testCompile" for your test classes, and "provided" is used for dependencies that are used at compile time, but not stored in your WAR file (because they're expected to be available in your web container).
The following posting might have relevant information: Compile, Provided, APK - Android dependency scope .

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.

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.

Categories

Resources