How to run unit tests with Android Studio - android

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.

Related

Error [DuplicatePlatformClasses] class conflict when building release on Room persistence

I have used this guide to build persistence with Room in my Android App:
https://developer.android.com/training/data-storage/room/index.html
and added dependances like shown here:
https://developer.android.com/topic/libraries/architecture/adding-components.html
when i build the debug version and deply to phone, everithing works fine.
When i build the release signed APK i got this error message:
Error:Error: json defines classes that conflict with classes now provided by Android. Solutions include finding newer versions or alternative libraries that don't have the same problem (for example, for httpclient use HttpUrlConnection or okhttp instead), or repackaging the library using something like jarjar. [DuplicatePlatformClasses]
my app.gradle:
apply plugin: 'com.android.application'
android {
signingConfigs {
/* TODO(developer): Configure to sign app with a release key for testing.
release {
storeFile file('path/to/release/signing/key')
keyAlias 'release_key_alias'
keyPassword "${password}"
storePassword "${password}"
}*/
}
compileSdkVersion 26
buildToolsVersion '26.0.2'
defaultConfig {
applicationId "myappid"
minSdkVersion 14
targetSdkVersion 23
versionCode 10
versionName "1.8"
}
buildTypes {
release {
minifyEnabled true
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
// TODO(developer): uncomment below once config above is complete and uncommented.
//signingConfig signingConfigs.release
}
}
}
configurations {
all {
exclude module: 'httpclient'
}
}
dependencies {
compile fileTree(include: ['*.jar'], dir: 'libs')
testCompile 'junit:junit:4.12'
compile 'com.android.support:appcompat-v7:26.1.0'
androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
exclude group: 'com.android.support', module: 'support-annotations'
})
compile 'com.android.support.constraint:constraint-layout:1.0.2'
compile 'com.android.volley:volley:1.0.0'
compile 'com.github.nkzawa:socket.io-client:0.3.0'
compile 'io.socket:socket.io-client:0.8.3'
compile 'com.android.support:design:26.1.0'
compile 'android.arch.persistence.room:runtime:1.0.0'
implementation "android.arch.persistence.room:runtime:1.0.0"
annotationProcessor "android.arch.persistence.room:compiler:1.0.0"
}
my project.gradle
buildscript {
repositories {
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:3.0.0'
//classpath 'io.socket:socket.io-client:0.8.3'
// NOTE: Do not place your application dependencies here; they belong
// in the individual module build.gradle files
}
}
ext{
roomVersion = '1.0.0'
}
allprojects {
repositories {
google()
jcenter()
maven { url 'https://maven.google.com' }
}
}
Somebody can help or give me clues?
I finally found the problem was a JSON sub-module:
compile 'com.github.nkzawa:socket.io-client:0.3.0'
this library has a submodule:
org.json:json
that is now conflicting with android native module, because in my other dependancies i can't find this one. It was working fine 10 days ago.
I also had to kill this:
compile 'io.socket:socket.io-client:0.8.3'
the final solution was to add an exclude for the module and change the line like this:
implementation ('com.github.nkzawa:socket.io-client:0.3.0',{
exclude group:'org.json', module:'json'
})
I also have noticed AFTER i solved the problem that in the error log it was suggesting me the module that was in conflict but even if i read it a hundred times i didn't noticed before:
so maybe google or Intellij could improve the writing of this errors...
To spot this class duplicate conflict error module i found the best way to proceed is to create a new project and paste in the dependancies in app build.gradle, and check them one by one or with "dividi et impera", maybe this is an obvious suggestion for someone but i would have like to have it sooner.
I had the same problem and I searched for the conflict via the gradle dependency tree:
gradlew app:dependencies
Then I excluded the the json module for the conflicting library:
implementation ('<conflicting-library>',{
exclude group:'org.json', module:'json'
})
How to find the duplicate library.
open gradle run window and run such command:
gradle module-name:dependencies
the "module-name" should be your app module's name, for me, it's "osmunda-demo".
then use Ctrl+F to search "commons-logging", you'll find it.
#Romeo has suggested a really great point. Was unable to debug the code for hours. The problem lies within the dependencies that are imported in build.gradle. It may be your own custom sdk/artifact. I had issues with my own library which uses jjwt. I added the exclusion in my sdk but you will have to add it again whenever using the sdk. Make sure to add exclude group: 'org.json', module: 'json' in your artifact implementation.

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'
}
}

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

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.

Multiple dex files define Lcom/google/firebase/FirebaseException

I encountered a problem with the Firebase integration. First of all, I have added rules to the root-level build.gradle file:
buildscript {
repositories {
maven { url "http://dl.bintray.com/populov/maven" }
jcenter()
}
dependencies {
classpath 'com.android.tools.build:gradle:2.1.2'
classpath 'com.google.gms:google-services:3.0.0'
}
}
allprojects {
repositories {
maven { url "http://dl.bintray.com/populov/maven" }
jcenter()
}
}
task clean(type: Delete) {
delete rootProject.buildDir
}
And the module Gradle file:
apply plugin: 'com.android.application'
android {
compileSdkVersion 24
buildToolsVersion "24"
defaultConfig {
applicationId "com.example.app"
minSdkVersion 14
targetSdkVersion 24
versionCode 2
versionName "0.9"
}
buildTypes {
///
}
}
dependencies {
compile fileTree(include: ['*.jar'], dir: 'libs')
compile 'com.google.firebase:firebase-core:9.0.2'
compile 'com.google.firebase:firebase-crash:9.0.2'
}
apply plugin: 'com.google.gms.google-services'
During the build of the project, I get the error:
Error:Error converting bytecode to dex: Cause:
com.android.dex.DexException: Multiple dex files define
Lcom/google/firebase/FirebaseException;
Error reason is clear, but I didn't compile any library twice. Should I exclude FirebaseException class from the build process manually? If so, how? Perhaps this is a bug within the Firebase dependencies?
Thanks.
I had this problem with react-native-google-signin module. As the instructions how to modify build.gradle are often not up to date, incomplete or just defined in multiple unrelated projects the project compiled only after copying the settings from the react-native-google-signin example project. It turns out the order of statements is important as well as exclude group command. The final result looked like this (in app/build.gradle):
dependencies {
...
compile 'com.google.android.gms:play-services-auth:9.2.1'
compile(project(":react-native-google-signin")) {
exclude group: "com.google.android.gms"
}
}
task copyDownloadableDepsToLibs(type: Copy) {
from configurations.compile
into 'libs'
}
apply plugin: 'com.google.gms.google-services'
The top build.gradle included an additional gms classpath as usual:
buildscript {
repositories {
jcenter()
mavenCentral()
}
dependencies {
classpath 'com.android.tools.build:gradle:2.2.2'
classpath 'com.google.gms:google-services:3.0.0'
}
}
After these changes build finished without any Multiple dex errors.
FireBase is a huge library, so you need to enable multidex support in your application.
dependencies {
compile ('com.google.firebase:firebase-core:9.0.2') {
exclude module: 'play-services-base'
exclude module: 'support-v4'
exclude module: 'support-annotations'
}
compile 'com.android.support:multidex:1.0.1'
}
defaultConfig {
// Enabling multidex support.
multiDexEnabled true
}
Looks like you have reached methods count limit. Try to remove firebase dependencies and check methods count for your app (for example, with this gradle plugin (if you don't remove these dependencies you won't be able to build your project at all, thus, to use the methods count plugin).
Firebase is a HUGE library - 17k+ methods. It depends on tons of stuff. One thing you can do is to check dependencies list by clicking this button on "methodscount.com":
If you already have some of these in your project you can try to exclude them:
compile ('com.google.firebase:firebase-core:9.0.2') {
exclude module: 'play-services-base'
exclude module: 'support-v4'
exclude module: 'support-annotations'
}
If this doesn't help then you might want to configure multidex for you project.
I am using react-native-maps and react-native-google-signin.
And, I got Multiple dex files define Lcom/google/firebase/FirebaseException
Bellow my solution.
Open build.gradle (react-native-maps)
dependencies {
provided "com.facebook.react:react-native:+"
compile "com.google.android.gms:play-services-base:10.2.4"
compile "com.google.android.gms:play-services-maps:10.2.4"
}
The version is 10.2.4
Continue open build.gradle (react-native-google-signin)
dependencies {
compile fileTree(include: ['*.jar'], dir: 'libs')
compile "com.android.support:appcompat-v7:23.0.1"
compile 'com.google.android.gms:play-services-auth:9.2.1' <- change here
compile "com.facebook.react:react-native:+"
}
It uses version 9.2.1, and this is reason.
Change it to version 10.2.4 will be
compile 'com.google.android.gms:play-services-auth:10.2.4'
Next, open build.gradle (app) and add a new one
compile 'com.google.android.gms:play-services-auth:10.2.4'
Now you have.
compile 'com.google.android.gms:play-services-auth:10.2.4'
compile(project(":react-native-google-signin")){
exclude group: "com.google.android.gms"
}
Run command cd android & gradlew clean & cd .. util no error then run react-native run-android.
Hope can help.
In case it helps anyone, I was hitting a similar problem, it was caused by the Gradle plugin for Google services bringing in a dependency which conflicted with Firebase.
In my top level build.gradle I had, in buildscript:
classpath 'com.google.gms:google-services:3.0.0'
Which was bringing in (automatically) dependencies which were conflicting with, in my app's build.gradle:
compile 'com.firebaseui:firebase-ui-auth:2.2.0'
Little bit confusing as I only had one compile dependency and was scratching my head what could be conflicing.
I removed the google-services gradle plugin and it solved the issue. I suppose I could also just find the right version :)
I encountered this error when I was using firebase-ui:2.0.0. I managed to solve it by downgrading to 'com.firebaseui:firebase-ui:1.2.0' and added the following line in Project level build.gradle:
allprojects {
repositories {
jcenter()
// Add the following
maven {
url 'https://maven.fabric.io/public'
}
}
}
Thanks to this post, just check and upgrade your google dependencies versions to the last release.
I could fix my problem. The problem was that BaseGameUtils was still
using/referencing an older version of play-services. Added the correct
version, and it works now. Guess I will omit BaseGameUtils for my next
project.
This is because some of your libraries use different versions of other library.
Check out your last added library and exclude.
For my project that was 'react-native-firestack'.
compile(project(':react-native-firestack')){
exclude group: "com.google.android.gms" // very important
}
Please add this code inside android in build.gradle
dexOptions {
preDexLibraries = false
}

Gradle: Error: more than one library with package name 'com.google.android.gms'

What does this error message mean? I don't have duplicated packages in my project
Error:Execution failed for task ':SimpleReader:processDebugResources'.
Error: more than one library with package name 'com.google.android.gms'
You can temporarily disable this error with
android.enforceUniquePackageName=false However, this is temporary and
will be enforced in 1.0
My build.gradle looks like this:
buildscript {
repositories {
maven { url 'http://repo1.maven.org/maven2' }
mavenCentral()
}
dependencies {
classpath 'com.android.tools.build:gradle:0.9.1'
}
}
apply plugin: 'android'
android {
buildToolsVersion '19.0.3'
defaultConfig {
minSdkVersion 14
targetSdkVersion 17
}
compileSdkVersion 17
packagingOptions {
exclude 'META-INF/DEPENDENCIES'
exclude 'META-INF/NOTICE'
exclude 'META-INF/LICENSE'
exclude 'META-INF/LICENSE.txt'
exclude 'META-INF/NOTICE.txt'
}
buildTypes {
}
}
dependencies {
compile 'com.android.support:support-v4:19.0.1'
compile 'com.google.android.gms:play-services:4.2.42'
compile files('libs/gson-2.2.4.jar')
compile files('libs/httpmime-4.1.jar')
compile files('libs/httpclient-4.1.1.jar')
compile files('libs/jsoup-1.7.3.jar')
compile project(':libraries:actionbarsherlock')
compile project(':libraries:sherlocknavigationdrawer')
compile project(':libraries:googleplayservices')
compile project(':libraries:androidslidinguppanel')
compile files('libs/protocol-1.0.4.jar')
compile files('libs/sentry-0.1.4.jar')
compile files('libs/commons-lang-2.3.jar')
}
In my case, the problem was because I was including:
compile 'com.google.android.gms:play-services-wearable:+'
compile 'com.google.android.gms:play-services:4.4.52'
both the wearable play services, and the regular.
I commented out the wearable part, and it works.
Not sure if I'll need it, but it was included by default by the project wizard
today I met the same problem. I need to use Google Analytics, so I import google analytics lib following the tutorial:
compile 'com.google.android.gms:play-services-analytics:9.0.0'
then compile the project, gradle tell me Error: more than one library with package name 'com.google.android.gms'
I can definitely sure that I only directly import com.google.android.gms one time by google analytics lib.
so I navigate to Project tab in Android Studio to see what are the libs this project depend on, then I found play-services-6.5.87 display in External Libraries, like following screenshot:
so now I know there is another lib depend on play-services-6.5.87, but I don't which lib it is.
then I use a gradle command in console to see the project dependencies:
$ ./gradlew -q app:dependencies
the result tells me that com.facebook.android:audience-network-sdk:4.6.0 depend on it.
so how we fix this problem, two way:
if you don't need this audience-network-sdk, just remove it. my project in fact doesn't need it.
if you also need audience-network-sdk and google-analytics, use exclude group grammar, like following snippet code.
//facebook SDK
compile ('com.facebook.android:audience-network-sdk:4.6.0')
{exclude group: 'com.google.android.gms'}
// google analytics
compile 'com.google.android.gms:play-services-analytics:9.0.0'
in your case, the audience-network-sdk can be any other lib that depends on same lib with other libs. here is just a thinking of how to resolve similar problems.
Try removing compile project(':libraries:googleplayservices') or compile 'com.google.android.gms:play-services:4.2.42'. I am pretty sure they are the same library.
I faced similar issue, i got it resolved by following steps:
ionic platform rm android
ionic platform add android
ionic build android
this is a problem with versions. if you have multiple dependencies of same package path ensure the versions are the same
compile 'com.google.android.gms:play-services-ads:8.4.0'
compile 'com.google.android.gms:play-services-gcm:8.4.0'
I had confused with this problem for a long time.My issue is little different with the question though same error log. I want my sublib's buildtype same with my application's buildtype. So I assigned the buildtype for sublib as the document tells me.
[Gradle Plugin User Guide][1]
This the error I got.
processing flavorCustomResource
Error: more than one library with com.xxx.libCommon
This is my structure. lib1 and lib2 are independent of each other.
app
-> lib1 -> libCommon
-> lib2 -> libCommon
I got the error only when I build my custom buildtype.However, The release version was Ok.
More details. some parts of my build.gradle
app:
android {
buildTypes {
release{}
custom{}
}
}
configurations {
flavorReleaseCompile
flavorCustomCompile
}
dependencies{
compile project(':lib1')
flavorReleaseCompile project(path: ':lib2', configuration: ':release')
flavorCustomCompile project(path: ':lib2', configuration: ':custom')
}
lib1:
android {
publishNonDefault true
buildTypes {
release{}
custom{}
}
}
dependencies{
releaseCompile project(path: ':libCommon', configuration: ':release')
customCompile project(path: ':libCommon', configuration: ':custom')
}
lib2
dependencies {
compile project(':libCommon')
}
Solution: configure the lib2 as lib1. the problem will be solved.
lib2:
android {
publishNonDefault true
buildTypes {
release{}
custom{}
}
}
dependencies{
releaseCompile project(path: ':libCommon', configuration: ':release')
customCompile project(path: ':libCommon', configuration: ':custom')
}
Reason
The problem is something about Library Publication
The default publish is release. if lib2 is not configured, it will use the default publish libCommon(release version) which is different from lib1 -> libCommon(custom version) assigned by lib1's build.gradle.This comes the error.
I wish my post will help someone struggle with the same issue or give some hint to him/her.

Categories

Resources