Inject UnitTest classes - java

Hello I have the following problem using Dagger 2 in my (part) project being completely pure-Java with no android dependencies.
When I run the unit tests using some mocks (e.g. Injecting a Mock Network Connector returning static Strings) over the Gradle view or console (businessModule:test) there are no problems and all tests Succeed. But when I open the files in Android Studio the Studio says that the Return of my DaggerMockComponent is not compatible with the target type. Opening the generated Component-Implementation, I see that Android Studio thinks the TestUnit-Class (and the interface MockComponent) is not available so it does not know what the inject method returns.
I have the following gradle file:
apply plugin: 'java'
// allow inject of core into core. https://github.com/griffio/dagger2-example
sourceSets {
dagger {
java {
srcDirs = ['src/dagger/java']
}
}
daggerTest {
java {
srcDirs = ['src/daggerTest/java']
}
}
}
configurations {
compileDagger
}
compileJava {
description = "dagger annotation processor is loaded automatically from classpath"
sourceSets.dagger.java.srcDirs*.mkdirs()
classpath += configurations.compileDagger
options.compilerArgs += [
'-s', sourceSets.dagger.java.srcDirs.iterator().next()
]
}
compileTestJava {
//dependsOn compileDaggerTestJava
description = "dagger annotation processor is loaded automatically from classpath"
sourceSets.daggerTest.java.srcDirs*.mkdirs()
classpath += configurations.compileDagger
options.compilerArgs += [
'-s', sourceSets.daggerTest.java.srcDirs.iterator().next()
//'-s src/testDaggerJava'
]
}
task deleteDagger(type: Delete) {
delete 'src/dagger', 'src/daggerTest'
}
clean.dependsOn deleteDagger
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
// Force Java 7 as newer versions can not be processed by dex for API 21
targetCompatibility = '1.7'
sourceCompatibility = '1.7'
[...]
// Dagger for dependency injection
compile 'com.google.dagger:dagger:2.8'
testCompile 'com.google.dagger:dagger:2.8'
compileOnly 'com.google.dagger:dagger-compiler:2.8'
testCompileOnly 'com.google.dagger:dagger-compiler:2.8'
[...]
testCompile 'junit:junit:4.12'
}
Thanks for your help.

Ok everybody, after an additional night and some research on the android-apt plugin I stumbled over the pure-Java apt (net.ltgt.apt) and now I have a working solution in combination with the idea-plugin
apply plugin: 'java'
apply plugin: "net.ltgt.apt"
apply plugin: "idea"
task cleanGenerated(type: Delete) {
delete 'build'
}
clean.dependsOn cleanGenerated
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
// Force Java 7 as newer versions can not be processed by dex for API 21
targetCompatibility = '1.7'
sourceCompatibility = '1.7'
[...]
// Dagger for dependency injection
compile 'com.google.dagger:dagger:2.8'
apt 'com.google.dagger:dagger-compiler:2.8'
testCompile 'com.google.dagger:dagger:2.8'
testApt 'com.google.dagger:dagger-compiler:2.8'
[...]
testCompile 'junit:junit:4.12'
}
Of course you have to add the dependency and plugin-name in the root gradle file but that is written down in the documentation for net.ltgt.apt - hope this works for you, too.

Related

Configure .jar to expose its dependencies

I have 3 modules: annotations, annotation_processor and app.
annotations/build.gradle
apply plugin: 'java-library'
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
}
annotation_processor/build.gradle
apply plugin: 'java-library'
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
api project(":annotations")
api "com.squareup:javapoet:1.11.1"
}
repositories {
mavenCentral()
}
sourceCompatibility = "1.8"
targetCompatibility = "1.8"
task deleteJar(type: Delete) {
delete 'libs/annotations.jar'
}
task createJar(type: Copy) {
from('build/intermediates/bundles/release/')
into('libs/')
include('classes.jar')
rename('classes.jar', 'annotations.jar')
}
createJar.dependsOn(deleteJar, build)
and app/build.gradle
dependencies {
...
implementation files('libs/annotation_processor.jar')
annotationProcessor files('libs/annotation_processor.jar')
...
}
When I run the project I get the following error.
error: package com.annotations does not exist
If I include annotations as a project the project I can skip this error but then I get.
Caused by: java.lang.NoClassDefFoundError: com/annotations/ProviderApi
at com.annotation_processor.ProviderAnnotationProcessor.getSupportedAnnotationTypes(ProviderAnnotationProcessor.java:45)
at org.gradle.api.internal.tasks.compile.processing.DelegatingProcessor.getSupportedAnnotationTypes(DelegatingProcessor.java:47)
at org.gradle.api.internal.tasks.compile.processing.NonIncrementalProcessor.getSupportedAnnotationTypes(NonIncrementalProcessor.java:33)
at org.gradle.api.internal.tasks.compile.processing.DelegatingProcessor.getSupportedAnnotationTypes(DelegatingProcessor.java:47)
at org.gradle.api.internal.tasks.compile.processing.TimeTrackingProcessor.access$101(TimeTrackingProcessor.java:37)
at org.gradle.api.internal.tasks.compile.processing.TimeTrackingProcessor$2.create(TimeTrackingProcessor.java:68)
at org.gradle.api.internal.tasks.compile.processing.TimeTrackingProcessor$2.create(TimeTrackingProcessor.java:65)
at org.gradle.api.internal.tasks.compile.processing.TimeTrackingProcessor.track(TimeTrackingProcessor.java:117)
at org.gradle.api.internal.tasks.compile.processing.TimeTrackingProcessor.getSupportedAnnotationTypes(TimeTrackingProcessor.java:65)
I can't access any of the dependencies (Java Poet and annotation module) from annotation_processor even though I have replaced implementation with api. Which should've expose the dependencies, but haven't.
I need the dependencies of the .jar file in the app module.
I'm new to Java Library and it may be I'm making a basic mistake, but can't seem to figure out, I've been at it for more than a day now.
You have to create a multi module gradle project.
I provide a small snippet of a multi module project.
project(':module1') {
dependencies {
compile project(':module-service-api')
compile 'org.apache.commons:commons-lang3:3.3.2'
compile 'log4j:log4j:1.2.17'
}
}
//module-app depends on module-service-impl
project(':module2') {
dependencies {
compile project(':module1')
}
For more details about multi module project, refer to the file build.gradle in the following project.
https://github.com/debjava/gradle-multi-module-project-1
If you want to create a fat jar or one jar, you have to include Gradle shadow plugin so that you can distribute the jar file along with other dependencies.
Refer below the link.
https://plugins.gradle.org/plugin/com.github.johnrengelman.shadow

Guava Dependency Breaking Jar Built With Kotlin

Issue
The Java/Kotlin application runs as expected in from the Main Class in IntelliJ's IDE. However, when the app is built into a .Jar file the following error occurs: java.lang.NoSuchMethodError: com.google.common.util.concurrent.MoreExecutors.
This is an issue with refactoring the directory, module, root project, and/or group names.
Reproducing Error
I've moved the project to a new directory path and everything runs as expected. However, after I attempt to modify the directory, and/or module names and refactor the rootProject.name in settings.gradle and the group in the build.gradle is when the error above appears when running a new .jar build.
Full Error Message
Exception in thread "Timer-0" java.lang.NoSuchMethodError: com.google.common.util.concurrent.MoreExecutors.directExecutor()Ljava/util/concurrent/Executor;
at io.grpc.internal.ClientCallImpl.<init>(ClientCallImpl.java:96)
at io.grpc.internal.ManagedChannelImpl$RealChannel.newCall(ManagedChannelImpl.java:662)
at io.grpc.internal.CensusTracingModule$TracingClientInterceptor.interceptCall(CensusTracingModule.java:382)
at io.grpc.ClientInterceptors$InterceptorChannel.newCall(ClientInterceptors.java:104)
at io.grpc.internal.CensusStatsModule$StatsClientInterceptor.interceptCall(CensusStatsModule.java:675)
at io.grpc.ClientInterceptors$InterceptorChannel.newCall(ClientInterceptors.java:104)
at com.google.api.gax.grpc.GrpcHeaderInterceptor.interceptCall(GrpcHeaderInterceptor.java:81)
at io.grpc.ClientInterceptors$InterceptorChannel.newCall(ClientInterceptors.java:104)
at com.google.api.gax.grpc.GrpcMetadataHandlerInterceptor.interceptCall(GrpcMetadataHandlerInterceptor.java:55)
at io.grpc.ClientInterceptors$InterceptorChannel.newCall(ClientInterceptors.java:104)
at io.grpc.internal.ManagedChannelImpl.newCall(ManagedChannelImpl.java:636)
at com.google.api.gax.grpc.GrpcClientCalls.newCall(GrpcClientCalls.java:66)
at com.google.api.gax.grpc.GrpcDirectCallable.futureCall(GrpcDirectCallable.java:58)
at com.google.api.gax.grpc.GrpcExceptionCallable.futureCall(GrpcExceptionCallable.java:62)
at com.google.api.gax.rpc.UnaryCallable$1.futureCall(UnaryCallable.java:126)
at com.google.api.gax.rpc.UnaryCallable.futureCall(UnaryCallable.java:87)
at com.google.cloud.firestore.FirestoreImpl.sendRequest(FirestoreImpl.java:330)
at com.google.cloud.firestore.UpdateBuilder.commit(UpdateBuilder.java:608)
at com.google.cloud.firestore.WriteBatch.commit(WriteBatch.java:41)
at com.google.cloud.firestore.DocumentReference.create(DocumentReference.java:141)
at com.google.cloud.firestore.CollectionReference.add(CollectionReference.java:115)
at com.google.cloud.firestore.CollectionReference.add(CollectionReference.java:141)
at PriceDifferenceTask.findMaxProfitAndPercentPriceDifference(PriceDifferenceTask.kt:167)
at PriceDifferenceTask.access$findMaxProfitAndPercentPriceDifference(PriceDifferenceTask.kt:15)
at PriceDifferenceTask$run$1.call(PriceDifferenceTask.kt:64)
at PriceDifferenceTask$run$1.call(PriceDifferenceTask.kt:15)
at rx.functions.Functions$6.call(Functions.java:169)
at rx.internal.operators.OperatorZip$Zip.tick(OperatorZip.java:252)
at rx.internal.operators.OperatorZip$Zip$InnerSubscriber.onNext(OperatorZip.java:323)
at rx.internal.util.ScalarSynchronousObservable$WeakSingleProducer.request(ScalarSynchronousObservable.java:276)
at rx.Subscriber.setProducer(Subscriber.java:211)
at rx.internal.util.ScalarSynchronousObservable$JustOnSubscribe.call(ScalarSynchronousObservable.java:138)
at rx.internal.util.ScalarSynchronousObservable$JustOnSubscribe.call(ScalarSynchronousObservable.java:129)
at rx.Observable.unsafeSubscribe(Observable.java:10256)
at rx.internal.operators.OperatorZip$Zip.start(OperatorZip.java:202)
at rx.internal.operators.OperatorZip$ZipSubscriber.onNext(OperatorZip.java:143)
at rx.internal.operators.OperatorZip$ZipSubscriber.onNext(OperatorZip.java:109)
at rx.internal.util.ScalarSynchronousObservable$WeakSingleProducer.request(ScalarSynchronousObservable.java:276)
at rx.Subscriber.setProducer(Subscriber.java:209)
at rx.internal.util.ScalarSynchronousObservable$JustOnSubscribe.call(ScalarSynchronousObservable.java:138)
at rx.internal.util.ScalarSynchronousObservable$JustOnSubscribe.call(ScalarSynchronousObservable.java:129)
at rx.internal.operators.OnSubscribeLift.call(OnSubscribeLift.java:48)
at rx.internal.operators.OnSubscribeLift.call(OnSubscribeLift.java:30)
at rx.Observable.subscribe(Observable.java:10352)
at rx.Observable.subscribe(Observable.java:10319)
at rx.Observable.subscribe(Observable.java:10159)
at PriceDifferenceTask.run(PriceDifferenceTask.kt:66)
at java.util.TimerThread.mainLoop(Timer.java:555)
at java.util.TimerThread.run(Timer.java:505)
Implementation
build.gradle
group 'coinverse'
version '1.0-SNAPSHOT'
buildscript {
ext.kotlin_version = '1.2.71'
ext.junitJupiterVersion = '5.0.3'
repositories {
mavenCentral()
}
dependencies {
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
classpath 'org.junit.platform:junit-platform-gradle-plugin:1.0.3'
}
}
apply plugin: 'java'
apply plugin: 'kotlin'
sourceCompatibility = 1.8
repositories {
mavenCentral()
}
dependencies {
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version"
testImplementation group: 'junit', name: 'junit', version: '4.12'
// JUnit Jupiter API and TestEngine implementation
testCompile("org.junit.jupiter:junit-jupiter-api:${junitJupiterVersion}")
testRuntime("org.junit.jupiter:junit-jupiter-engine:${junitJupiterVersion}")
testCompile("org.assertj:assertj-core:3.10.0")
// To avoid compiler warnings about #API annotations in JUnit code
testCompileOnly('org.apiguardian:apiguardian-api:1.0.0')
implementation 'com.squareup.retrofit2:retrofit:2.4.0'
implementation 'com.squareup.retrofit2:converter-gson:2.4.0'
implementation 'com.squareup.retrofit2:adapter-rxjava:2.4.0'
implementation 'io.reactivex.rxjava2:rxjava:2.2.2'
implementation 'com.google.firebase:firebase-admin:6.5.0'
}
compileKotlin {
kotlinOptions.jvmTarget = "1.8"
}
compileTestKotlin {
kotlinOptions.jvmTarget = "1.8"
}
Gradle Dependency Tree
Attempted Solutions
After examining similar issues on StackOverflow this appears to be related to a conflict with Google's Guava library. From the Gradle Dependencies above some libraries were calling older versions of Guava. All libraries in the build.gradle have been updated to their latest versions.
Rebuilding project.
IntelliJ Invalidate Cache and Restart
Implementing current version of Guava in build.gradle: api "com.google.guava:guava:27.0-jre"
Implementing lowest version of Guava in build.gradle found in dependency tree: implementation 'com.google.guava:guava:19.0'
Implementing highest version of Guava in build.gradle found in dependency tree: implementation 'com.google.guava:guava:20.0'
Attempting to exclude lowest version of Guava in build.gradle found in dependency tree: configurations {all*.exclude 'com.google.guava:guava:19.0'}
add the current version 27.0:
dependencies {
api "com.google.guava:guava:27.0-jre"
}
and exclude both other versions 19.0 and 20.0, wherever they may be referenced.
./gradlew app:dependencies > dependencies.txt
or check with:
./gradlew app:dependencies | grep guava
for example (the firebase-admin is certainly a candidate):
// https://mvnrepository.com/artifact/com.google.firebase/firebase-admin
implementation ("com.google.firebase:firebase-admin:6.5.0") {
exclude group: "com.google.guava", module: "guava"
}
there may be further references present.
Solution
The Jar build started working again after updating my library dependencies and redefining the Project level SDK when re-pulling a version built on a different machine from Github.
Update to dependencies
Changed compile to implementation.
Updated version numbers by searching for each project's latest version on Google.
build.grade
buildscript {
ext.kotlin_version = '1.3.10'
ext.junitJupiterVersion = '5.3.2'
repositories {
mavenCentral()
}
dependencies {
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
classpath 'org.junit.platform:junit-platform-gradle-plugin:1.0.3'
}
}
plugins {
id 'java'
id 'org.jetbrains.kotlin.jvm' version '1.2.51'
}
version '1.0-SNAPSHOT'
sourceCompatibility = 1.8
repositories {
mavenCentral()
}
dependencies {
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk8"
testImplementation group: 'junit', name: 'junit', version: '5.3.2'
// JUnit Jupiter API and TestEngine implementation
testImplementation("org.junit.jupiter:junit-jupiter-api:${junitJupiterVersion}")
testRuntime("org.junit.jupiter:junit-jupiter-engine:${junitJupiterVersion}")
testImplementation "org.assertj:assertj-core:3.11.1"
// To avoid compiler warnings about #API annotations in JUnit code
testCompileOnly 'org.apiguardian:apiguardian-api:1.0.0'
implementation 'com.squareup.retrofit2:retrofit:2.5.0'
implementation 'com.squareup.retrofit2:converter-gson:2.5.0'
implementation 'com.squareup.retrofit2:adapter-rxjava:2.5.0'
implementation 'io.reactivex.rxjava2:rxjava:2.2.4'
implementation 'com.google.firebase:firebase-admin:6.6.0'
implementation 'com.google.apis:google-api-services-youtube:v3-rev206-1.25.0'
}
compileKotlin {
kotlinOptions.jvmTarget = "1.8"
}
compileTestKotlin {
kotlinOptions.jvmTarget = "1.8"
}

How to properly set up Lombok in Android Studio 3.0

I would like to know what am I doing wrong in the Lombok setup for Android Studio 3.0 Beta 2?
That's how my Gradle build file looks like:
buildscript {
repositories {
mavenCentral()
jcenter()
maven { url "https://plugins.gradle.org/m2/" }
}
dependencies {
classpath "io.franzbecker:gradle-lombok:1.10"
classpath 'com.android.tools.build:gradle:2.3.3'
}
}
allprojects {
apply plugin: "eclipse"
apply plugin: "idea"
version = '1.0'
ext {
appName = "MyAppName"
gdxVersion = '1.7.0'
}
repositories {
mavenCentral()
maven { url "https://oss.sonatype.org/content/repositories/snapshots/" }
maven { url "https://oss.sonatype.org/content/repositories/releases/" }
}
}
project(":desktop") {
apply plugin: "java"
dependencies {
compile project(":core")
compile "com.badlogicgames.gdx:gdx-backend-lwjgl:$gdxVersion"
compile "com.badlogicgames.gdx:gdx-platform:$gdxVersion:natives-desktop"
}
}
project(":android") {
apply plugin: "android"
configurations { natives }
dependencies {
compile project(":core")
compile "com.badlogicgames.gdx:gdx-backend-android:$gdxVersion"
natives "com.badlogicgames.gdx:gdx-platform:$gdxVersion:natives-armeabi"
natives "com.badlogicgames.gdx:gdx-platform:$gdxVersion:natives-armeabi-v7a"
natives "com.badlogicgames.gdx:gdx-platform:$gdxVersion:natives-x86"
}
}
project(":core") {
apply plugin: "io.franzbecker.gradle-lombok"
apply plugin: "java"
dependencies {
compile "com.badlogicgames.gdx:gdx:$gdxVersion"
compile "com.badlogicgames.gdx:gdx-freetype:$gdxVersion"
compileOnly "org.projectlombok:lombok:1.16.18"
}
}
tasks.eclipse.doLast {
delete ".project"
}
I have installed the lombok plugin, and lombok stuff also shows up properly in the IDE, but when I want to build the project Gradle can not find the getters/setters created by Lombok. I tried to follow the tutorials from https://projectlombok.org/setup/android and other stack overflow pages about this setup, but nothing worked. In Android Studio 2.3 I couldn't even enable the annotation processing properly, that's why I updated to the latest beta version, where that at least works.
I have the same issue. At last I end up with this solution -
compileOnly 'org.projectlombok:lombok:1.16.18'
compileOnly 'javax.annotation:javax.annotation-api:1.3.1'
annotationProcessor 'org.projectlombok:lombok:1.16.18'
You need to use new annotationProcessor instead of apt : Gradle migration annotationProcessor
annotationProcessor "org.projectlombok:lombok:1.16.18"
I had the same problem as you and now it works.
I was facing the same issue where upgrading AS to 3.0 and Gradle to 4.1, lombok stopped generating setters/getters.
So If you are using lombok plugin with IntelliJ then for me downgrading lombok from latest stable edge release to 0.15.17.2 solved it.
This issue helped me solving it

Is there any way of making IntelliJ IDEA recognizing Dagger 2 generated classes in a Java project?

Context
I have started a personal project in java with Gradle as the build system and I want to use Dagger 2 as a DI. The main reason of doing that is to get used to that library and be able to use it easily in bigger projects.
What have I tried
I've managed to make the Google sample runs on IntelliJ IDEA
Problem
IntelliJ IDEA keeps telling me that it cannot resolve the generated class (in this case DaggerCoffeeApp_Coffee). It's a bit annoying not to know if the written code is correct (specially when you are learning to use Dagger 2).
All java classes are the same as the Google sample. Here is my build.gradle file:
apply plugin: 'java'
repositories {
mavenCentral()
}
dependencies {
testCompile group: 'junit', name: 'junit', version: '4.12'
compile 'com.google.dagger:dagger:2.0.1'
compile 'com.google.dagger:dagger-compiler:2.0.1'
}
Question
Is there any way to make IntelliJ IDEA recognize DaggerCoffeeApp_Coffee as a generated class (and so make it possible to go to its implementation by `ctrl + left click)?
Simplest way I found:
Add idea plugin and add Dagger2 dependency like below:
plugins {
id "net.ltgt.apt" version "0.10"
}
apply plugin: 'java'
apply plugin: 'idea'
sourceCompatibility = 1.8
repositories {
mavenCentral()
}
dependencies {
testCompile group: 'junit', name: 'junit', version: '4.12'
compile 'com.google.dagger:dagger:2.11'
apt 'com.google.dagger:dagger-compiler:2.11'
}
Turn on Annotation Processing for IntelliJ: Go to Settings and search for Annotation Processors, check Enable annotation processing like below image:
Finally I made it!
I had to add the apt and the idea plugin so right now my build.gradle file look like this:
buildscript {
repositories {
maven {
url "https://plugins.gradle.org/m2/"
}
}
dependencies {
classpath "net.ltgt.gradle:gradle-apt-plugin:0.4"
}
}
apply plugin: "net.ltgt.apt"
apply plugin: 'java'
apply plugin: 'idea'
repositories {
mavenCentral()
}
dependencies {
testCompile group: 'junit', name: 'junit', version: '4.12'
compile 'com.google.dagger:dagger:2.0.1'
apt 'com.google.dagger:dagger-compiler:2.0.1'
}
you must manually enable the annotation processing in IntelliJ.
From: Settings --> Build, Execution, Deployment --> Compiler --> Annotation Processors --> Enable annotation processing and Obtain processors from project classpath
then rebuild the project and you will find the generated classes in the project.
Please note that I have used this solution in a (java) android project.
I'm using version 2017.3.3 of IntelliJ IDEA, version 0.14 of the net.ltgt.apt plugin and version 2.14.1 of Dagger and as well as applying the idea plugin in the build.gradle file (as in Pelocho's answer) I found I also had to tell IntelliJ where it can find the sources generated by Dagger, as follows:
apply plugin: 'idea'
idea {
module {
sourceDirs += file("$buildDir/generated/source/apt/main")
testSourceDirs += file("$buildDir/generated/source/apt/test")
}
}
This is what I had to do in order to get Idea to work with Dagger2 and gradle.
Turn on annotation processing as shown in the answers above.
Add the following to the build.gradle file in order for Idea to see the generated classes as sources.
sourceDirs += file("$projectDir/out/production/classes/generated/")
Here's the full listing of my build.gradle
plugins {
id 'java'
id 'idea'
id "net.ltgt.apt" version "0.10"
}
idea {
module {
sourceDirs += file("$projectDir/out/production/classes/generated/")
}
}
repositories {
mavenCentral()
}
dependencies {
compile 'com.google.dagger:dagger:2.16'
apt 'com.google.dagger:dagger-compiler:2.16'
}
sourceCompatibility = 1.8
Also, I had to add the following gradle task (to my build.gradle file) to clear out my out directory. When I moved some files around and Dagger2 regenerated the source files, the out directory wasn't being cleared out :(. I also included this task in my run configuration, so that it gets triggered before I rebuild my project.
task clearOutFolder(type: Delete) {
delete 'out'
}
Here's the solution that worked for me:
File -> Project Structure -> (select your project under list of modules) -> Open 'Dependencies' tab
Then, click on green '+' sign, select 'JARs or directory' and select 'build/classes/main' folder.
Another solution would be to link folder with build class files using 'dependencies' block inside build.gradle:
https://stackoverflow.com/a/22769015/5761849
Using IntelliJ IDEA 2019.1 and Gradle 5.4.1, this seems to be enough:
plugins {
id 'java'
}
version '1.0-SNAPSHOT'
sourceCompatibility = 1.8
repositories {
mavenCentral()
}
dependencies {
testImplementation group: 'junit', name: 'junit', version: '4.12'
implementation 'com.google.dagger:dagger:2.23.1'
annotationProcessor 'com.google.dagger:dagger-compiler:2.23.1'
}
I don't know the minimal versions for which this solution works, though.
I had a similar problem, I could not find out the cause for a long time.
Just launched and the result surprised me.
Intellij Idea 2018.3.6 -
build.gradle:
plugins {
id "java"
}
sourceCompatibility = 1.8
repositories {
mavenCentral()
}
dependencies {
testCompile group: 'junit', name: 'junit', version: '4.12'
compile 'com.google.dagger:dagger:2.11'
apt 'com.google.dagger:dagger-compiler:2.11'
}
The following worked for me on IntelliJ 2021.3.3 (UE)
plugins {
id 'java'
id 'idea'
id("com.github.johnrengelman.shadow") version "7.1.2"
}
idea {
module {
sourceDirs += file("$projectDir/build/generated/sources/annotationProcessor/java/main")
testSourceDirs += file("$projectDir/build/generated/sources/annotationProcessor/java/test")
}
}
group 'com.codigomorsa'
version '1.0-SNAPSHOT'
repositories {
mavenCentral()
}
dependencies {
annotationProcessor 'com.google.dagger:dagger-compiler:2.44'
implementation 'com.google.code.gson:gson:2.9.1'
implementation 'com.google.dagger:dagger:2.44'
testAnnotationProcessor 'com.google.dagger:dagger-compiler:2.44'
testImplementation 'org.junit.jupiter:junit-jupiter-api:5.9.0'
testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.9.0'
}
test {
useJUnitPlatform()
}

How To Include Transitive Dependencies

I have 2 gradle projects: an Android app and a RoboSpock test.
My build.gradle for the Android app has
. . .
dependencies {
compile fileTree(dir: 'libs', include: '*.jar')
compile ('com.actionbarsherlock:actionbarsherlock:4.4.0#aar') {
exclude module: 'support-v4'
}
}
. . .
and builds correctly by itself, e.g assembleRelease works.
I'm stuck getting the test to work. I gets lots of errors such as:
package com.google.zxing does not exist
Those seem to indicate that the .jar files aren't being picked up.
Here's my build.gradle for the test project:
buildscript {
repositories {
mavenLocal()
mavenCentral()
}
dependencies {
classpath 'com.android.tools.build:gradle:0.9.+'
classpath 'org.robospock:robospock-plugin:0.4.0'
}
}
repositories {
mavenLocal()
mavenCentral()
}
apply plugin: 'groovy'
dependencies {
compile "org.codehaus.groovy:groovy-all:1.8.6"
compile 'org.robospock:robospock:0.4.4'
}
dependencies {
compile fileTree(dir: ':android:libs', include: '*.jar')
compile (project(':estanteApp')) {
transitive = true
}
}
sourceSets.test.java.srcDirs = ['../android/src/', '../android/build/source/r/debug']
test {
testLogging {
lifecycle {
exceptionFormat "full"
}
}
}
project.ext {
robospock = ":estanteApp" // project to test
}
apply plugin: 'robospock'
As that shows, I've tried adding transitive = true and including the .jar files explicitly. But no matter what I try, I end up with the package does not exist error.
In Android Studio you no longer need a different project for testing. Put your testing code in the same module under "src/androidTest/java"
Then add the following to "build.gradle" in the "defaultConfig"
testPackageName "com.yourpackage.test"
testInstrumentationRunner "android.test.InstrumentationTestRunner"
testFunctionalTest true

Categories

Resources