Android: Unresolved reference when using junit 4.13 - android

After updating junit version to 4.13 in gradle dependencies, classes and annotations like Assert, #Test, etc. under the junit package are displayed as red when used in my code. Lint check says:
Unresolved reference: <any junit class>
However, when I build and run my tests, it will build and run just fine.
I have tried:
restarting Android Studio
Invalidate caches and restart
Clean and rebuild project
added testImplementation "org.jetbrains.kotlin:kotlin-test-junit:$kotlin_version"
What works is downgrading junit to 4.12. How to get rid of this lint error, without downgrading version?
Update:
When I check ALT + ENTER options and select Inspection 'Unresolved reference, in wrong test scope' options > Suppress 'IncorrectScope' for file <name of file>, it gets rid of these lint errors for that particular file. I still like to solve this problem without using Suppress though.
According to this issue, it looks like this bug is not fixed yet. For now I'm downgrading to 4.12.
Removing both espresso and runner from dependencies also fixes the problem.

Just add the following to your build.gradle (App) file:
configurations.all {
resolutionStrategy.force "junit:junit:$junit_version"
}
dependencies {
...
}

The first of all check your external dependencies
In my case I found double jUnit versions which is
Junit 4.12
Junit 4.13
And the older version is come with androidx.test
The solution is
1. exclude dependencies
or
2. remove `androidx.test`
or
3. add conflict startegy

Borrowing from #VaheGharibyan's idea about duplicate junit versions, I discovered that the following code also fixes the problem.
configurations.all {
resolutionStrategy.dependencySubstitution {
substitute module('junit:junit:4.12') with module('junit:junit:4.13')
}
}

Related

Upgrading Android kotlin version to 1.5.0 throwing error message on build

Running with kotlin version '1.4.32' my Android project runs and builds. Trying to upgrade to kotlin '1.5.0' and my build throws:
Execution failed for task ':app:kaptDefaultsDebugKotlin'.
> A failure occurred while executing org.jetbrains.kotlin.gradle.internal.KaptWithoutKotlincTask$KaptExecutionWorkAction
> java.lang.reflect.InvocationTargetException (no error message)
I am not even sure where to start looking. Anyone else have problems upgrading to kotlin 1.5.0?
I experienced the same issue today. Ran the gradle build command with --stacktrace and got a helpful stacktrace which narrowed down the issue to Moshi library.
Caused by: java.lang.IllegalStateException: Could not parse metadata! This should only happen if you're using Kotlin <1.1.
at com.squareup.moshi.kotlinpoet.metadata.KotlinPoetMetadata.readKotlinClassMetadata(KotlinPoetMetadata.kt:70)
at com.squareup.moshi.kotlinpoet.metadata.KotlinPoetMetadata.toImmutableKmClass(KotlinPoetMetadata.kt:50)
at com.squareup.moshi.kotlin.codegen.MoshiCachedClassInspector.toImmutableKmClass(MoshiCachedClassInspector.kt:22)
at com.squareup.moshi.kotlin.codegen.MetadataKt.targetType(metadata.kt:109)
at com.squareup.moshi.kotlin.codegen.JsonClassCodegenProcessor.adapterGenerator(JsonClassCodegenProcessor.kt:136)
at com.squareup.moshi.kotlin.codegen.JsonClassCodegenProcessor.process(JsonClassCodegenProcessor.kt:110)
at org.jetbrains.kotlin.kapt3.base.incremental.IncrementalProcessor.process(incrementalProcessors.kt:90)
at org.jetbrains.kotlin.kapt3.base.ProcessorWrapper.process(annotationProcessing.kt:175)
at jdk.compiler/com.sun.tools.javac.processing.JavacProcessingEnvironment.callProcessor(JavacProcessingEnvironment.java:980)
... 41 more
Had to update Moshi to 1.12.0 and that did the trick.
Here's a changelog for Moshi 1.12.0 that mentions the fix for 1.5.0: https://github.com/square/moshi/blob/master/CHANGELOG.md#version-1120
Issue when it was first reported here: https://github.com/square/moshi/issues/1324
Another issue which mentions the fix here: https://github.com/square/moshi/issues/1337
So I'd suggest you run gradle build command with --stacktrace and figure out which library causes the incompatibility with the kotlinx-metadata-jvm library and update it.
This is due to Dagger's use of older version of kotlinx-metadata-jvm.
See https://youtrack.jetbrains.com/issue/KT-45885
Update your dagger to 2.34
In my case dagger caused the issue.
Updating the dependency worked out.
implementation 'com.google.dagger:dagger:2.37'
kapt 'com.google.dagger:dagger-compiler:2.37'
This issue resurfaced for me after upgrading my project to Kotlin 1.6.0. In my case it's because of the Moshi JSON serialization lib. They have already included a fix in their next release. In the meantime, I have reverted back to 1.5.31.
https://github.com/square/moshi/issues/1433
I had this issue while upgrading Kotlin version to 1.6.10
To fix, I had to update the dagger version to 2.36 or higher and I used 2.40.5
implementation "com.google.dagger:dagger:2.40.5”
kapt "com.google.dagger:dagger-compiler:2.40.5"
To find latest dagger versions - https://github.com/google/dagger/releases
If other answers didn't help you, and especially if you're on alpha or beta version of Android Studio, make sure that you using JDK embedded with Android Studio. It was my case, i did use external downloaded JDK.
To change JDK go to File -> Settings -> Build, Execution, Deployment -> Build Tools -> Gradle and select Embedded JDK from dropdown Gradle JDK.
You should check which of your dependencies probably depends on new kotlin changes in version 1.5.0 and try to update them.
For me the room and dagger was causing problems, i've upgraded it to the latest versions and now i have no problems:
room to : 2.3.0
dagger to : 2.35.1
It might not necessarily be dagger or moshi. It can be any library that uses kapt (kotlin annotation processor). Look for kapt in your build.gradle and try to update everything that uses it.
For me it was a library which was using an older version of kotlinpoet.
You should update hilt to 2.42 for kotlin 1.7
I had same issue during build:
KaptWithoutKotlincTask$KaptExecutionWorkAction
I had a data binding issue in one of my XML, which threw this error.
This was my case:
abc.xml
<layout xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto">
    <data>
    </data>
    <TextView
android:text="#{object.name}"
... />
</layout>
object variable was not declared. After declaration, it resolved the build issue.
The error message did not point to the correct location in my case.
yes in my case recently i solved the problem by updating dagger to latest version and gradle update to latest version as well as using latest jdk
I have same issue, and finally solved by update moshi to 1.12.0
My dagger error message looked as follows:
error: [androidprocessor:miscerror]
dagger.android.processor.androidprocessor was unable to process this
class because not all of its dependencies could be resolved. check for
compilation errors or a circular dependency with generated code.
I also had this kapt error: java.lang.reflect.InvocationTargetException (no error message)
I was given which file dagger was not able to properly process, but no exact information on missing dependency. I applied all the fixes I found in this so. I had to carefully examine all the dependencies I could see in the generated by dagger file for which error was shown.
In my case it was dagger not able to find org.jetbrains.annotations.NotNull. I noticed this dependency was upgraded, and due to some fixes I moved to use androidx.annotation.NonNull in my code. I actually didnt depend on org.jetbrains.annotations - it was being included from some other dependency. The error looked as follows:
found in modules jetified-annotations-12.0
(com.intellij:annotations:12.0) and jetified-annotations-16.0.1
(org.jetbrains:annotations:16.0.1)
I was resolving conflicts which ended up so that dependency was not visible by dagger.
As usual in such cases it was very usefull to see dependecy tree and where dependencies are comming from. Some dependencies were outdated and used org.jetbrains:annotations in older version, and I had to either upgrade them or block this dependency from being included in my code with exclude, for example:
implementation ("io.reactivex.rxjava2:rxkotlin:$rxKotlinVersion") {
exclude group: 'org.jetbrains', module: 'annotations'
}
for dependency tree listing see here: How do I show dependencies tree in Android Studio?
Got this error due to Gradle not recognizing some of my modules. Re-syncing settings.gradle fixed this for me.
Go to https://mvnrepository.com/artifact/com.google.dagger/hilt-android-gradle-plugin to get the latest hilt version.
Then, update the project build.gradle and update to the latest version:
dependencies {
classpath('com.google.dagger:hilt-android-gradle-plugin:2.43.2')
}
Do the same for the app build.gradle
dependencies {
implementation("com.google.dagger:hilt-android:2.43.2")
kapt("com.google.dagger:hilt-android-compiler:2.43.2")
}

How would you troubleshoot dependency errors that arise in Release mode only in Android?

Context
We have an Android app built in Kotlin and we've split our algorithms layer into a separate Android Project. We import that as a dependency using Gradle using the following code:
In build.gradle:
dependencies {
...
implementation project(':algos-android')
}
This algos-android project has its own dependency - koma - defined in the algos-android project's build.gradle file as follows:
dependencies {
...
implementation group: "com.kyonifer", name:"koma-core-ejml", version: "0.12"
}
Issue
This works completely fine when running the app in a debug mode (defined in buildTypes in the build.gradle). However, when running in release mode, we are seeing an error at runtime when our algorithms layer uses its sub-dependency - koma.
The following error shows up in the console:
java.lang.IllegalStateException: No double matrix factories available. (Did you forget to import a koma-core implementation?)
My team was under the assumption that Gradle handles sub-dependencies for us. Has anyone run into issues like this before? Are there any good debug approaches?
Things We've Tried
Moving all of the files from our algos-android project directly into the main project and importing koma directly in the main project's gradle.build file.
Environment
Android Studio 4.0.1
Kotlin Version 1.3.72
Gradle Version 6.3
Subdependency Repo:
https://github.com/kyonifer/koma
We were finally able to track down the issue and resolve this with the following addition to the proguard-rules.pro file:
-keep class koma.** { *; }
We were able to find that since the Matrix factory classes are inflated in koma sources using reflection, proguard considered them as unused and simply deleted them from the release build.
Note: If you see this and make this fix, don't forget to Clean Project before running.

Android Studio 2.4 + Lombok annotationProcessor configuration confusion

I using lombok on some project, and with the new Android Studio 2.4 Update now (Preview) I get this strange error:
What went wrong: Execution failed for task
':core:javaPreCompileRelease'. Annotation processors must be
explicitly declared now. The following dependencies on the compile
classpath are found to contain annotation processor. Please add them
to the annotationProcessor configuration.
- lombok-1.16.16.jar Alternatively, set android.defaultConfig.javaCompileOptions.annotationProcessorOptions.includeCompileClasspath
= true to continue with previous behavior. Note that this option is deprecated and will be removed in the future. See
https://developer.android.com/r/tools/annotation-processor-error-message.html
for more details.
I already tried:
annotationProcessor "org.projectlombok:lombok:1.16.16"
but has no effect.
I also tested:
android.defaultConfig.javaCompileOptions.annotationProcessorOptions.includeCompileClasspath
= true
But also has no effect.
Also checked the support page for further information but with no luck, anyone of you possibly?
https://developer.android.com/studio/preview/features/index.html?utm_source=android-studio#annotationProcessor_config
Update:
provided "org.projectlombok:lombok:1.16.16" // keep
annotationProcessor "org.projectlombok:lombok:1.16.16" // add this
Just worked perfectly, but I have two Android Studio modules, and two build.gradle files.
The error log just changed a bit (module prefix), and I thought the fix didn't work.
But after applying the fix to both build.gradle files everything worked perfectly.
I had the same problem but needed a slightly different fix (although the idea came from the accepted answer above - https://stackoverflow.com/a/43820494/1777346)
Turned out I already had the provided and annotationProcessor in both build.gradle files.. but, I also had a compile entry. Removing it fixed this issue for me:
compile 'org.projectlombok:lombok:1.16.16' // remove this
provided 'org.projectlombok:lombok:1.16.16'
annotationProcessor "org.projectlombok:lombok:1.16.16"
Just figured I'd add my findings in case it helps anyone. I'm using Android Studio 3.0 Canary 4 and gradle:3.0.0-alpha4 in my unending quest to get build times down.. which never seems to pay off :)

JUnit not working on IntelliJ Android project

http://www.tutorialspoint.com/junit/junit_environment_setup.htm
I have done everything like in this step by step tutorial and still when I try to write the line
import org.junit.*;
The "junit" part is lighten red and the error message is "cannot resolve symbol "junit"".
The tutorial you are following seems to be written for command line usage. (Download jar, set classpath etc). So the same wouldn't work in IntelliJ.
IDEs actually make these a lot easier.
To solve your current dilemma, try this. Place the cursor on the red 'junit' (which is basically a broken import) and choose "Add Junit4 to classpath". This will add the necessary junit jars that IDEA ships with to your classpath.
Open up your build.gradle and make sure JUnit is there
dependencies {
testCompile 'junit:junit:4.12'
// other dependencies...
}
And for a better link for Android-specifics, read Getting Started with Testing from the Android docs.

How to add testCompile dependencies to IDE classpath

I have been struggling with unit-test-android problem for quite a long time. I have seen this, this and that, finally I found the gradle-android-test-plugin and even got it working. I can now run the tests with gradlew test command.
But, writing those tests in IDE (Android Studio or IntelliJ 13) is far from comfortable, because it does not see the junit & Robolectric dependencies added with testCompile dependency.
Is there any way to add these dependencies to the IDE classpath but still avoid to package them in the production app (thus, AFAIU compile dependency cannot be used)?
I had the same problem with IntelliJ 14.1.3 today. The solution was to run the steps outlined here. Basically:
Add JUnit and other dependencies via testCompile 'junit:junit:4.+', etz
Put test sources in src/test/java/...
To make the IDE find the test-dependencies (gradle will find them fine), open the "Build Variants"-view and set "Test Artifact" to "Unit Test". In "Project Structure", the testing dependencies should show up in your module with the "Test"-scope
The commandline to run a test is testXxx, where Xxx is the build-type (debug/release/etz).
The important step here is the one in the "Build Variants" view. After you change it to "Unit Test", it will index and your libraries and full auto-completion are available.
For my Android test dependencies, I use instrumentTestCompile instead of testCompile. This works for me when running my tests in Android Studio. Hope this helps.
You can use the built-in idea plugin. That should set up test dependencies for you. You'll need to import the plugin:
apply plugin: 'idea'
Then run gradle idea, to generate module file (*.iml) and re-load your project. Note you'll have to be using non-directory based idea configuration for this to work.
In IntelliJ IDEA you need to configure couple things in your build.gradle
// add idea plugin
apply plugin: 'idea'
// make sure `configurations.testCompile` is added to idea.module
idea {
module {
scopes.TEST.plus += [ configurations.testCompile ]
}
}
For more info see:
http://www.gradle.org/docs/current/dsl/org.gradle.plugins.ide.idea.model.IdeaModule.html
Any dependency included with testCompile will be automatically imported into IDEA.

Categories

Resources