Dagger not generating components for /test class - android

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.

Related

Kotlin Unit Test Not Finding Module Dependency Interface

I have an app module and a domain module. In my domain module I have an interface called Repository. In my app module I use dagger to inject an implementation for this into my class and this works fine.
When I then go to test it using a kotlin unit test, at runtime I get a NoClassDefFoundError.
I have also tried to include the domain module in my app modules dependencies like so but that also did not work:
testImplementation project(':domain')
Here are my current test dependencies and also how I'm including the module
implementation project(':domain')
testImplementation 'junit:junit:4.12'
testImplementation 'com.nhaarman:mockito-kotlin:1.5.0'
In my unit test I'm using it like this which could be the issue:
#Mock lateinit var mockRepo : Repository
Thanks to #Mark Keen, I was able to find a reported bug on the Jetbrains site.
This contained a solution from a user called #Calin. Adding the following to the projects's build.gradle file and triggering a gradle sync does the trick.
subprojects { subProject ->
afterEvaluate {
if (subProject.plugins.hasPlugin("kotlin") && subProject.plugins.hasPlugin("java-library")) {
subProject.kotlin.copyClassesToJavaOutput = true
subProject.jar.duplicatesStrategy = DuplicatesStrategy.EXCLUDE
}
}
}

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.

Use Dagger generated test code in Android

I'm trying to use Dagger2 in my android project as explained in hitherejoe/Android-Boilerplate. While I am setting up the project I got following error on build time.
Error:(30, 26) error: cannot find symbol variable DaggerTestComponent
After digging into the documentation and generated code I figured out that code is not generating in debug (/app/build/generated/source/apt/debug/) folder but in test/debug(/app/build/generated/source/apt/test/debug) folder.
So in my test source folder can not import the generated DaggerTestComponent.
Any clue how to include test/debug folder to the source?
My dependancies are as follows
testCompile 'com.neenbedankt.gradle.plugins:android-apt:1.8'
compile "com.google.dagger:dagger:$DAGGER_VERSION"
apt "com.google.dagger:dagger-compiler:$DAGGER_VERSION"
provided 'javax.annotation:jsr250-api:1.0'
compile 'javax.inject:javax.inject:1'
testApt "com.google.dagger:dagger-compiler:$DAGGER_VERSION"
Thanks in advance.
I had the same problem... I worked around it by adding the generated test source directory:
android {
sourceSets {
// add dagger generated files (works only with debug build)
test.java.srcDirs += ['build/generated/source/apt/test/debug']
}
}
Use:
// Dagger 2
provided "javax.inject:javax.inject:1"
compile "com.google.dagger:dagger:$DAGGER_VERSION"
apt "com.google.dagger:dagger-compiler:$DAGGER_VERSION"

Gradle - add dependency to tests of another module

I have a multi-module gradle project that looks like this:
Parent
|--server
|--application (android module)
+--common
The server tests have a dependency on the common module tests. For this, I added
testCompile files(project(':common').sourceSets.test.output.classesDi
compileTestJava.dependsOn tasks.getByPath(':common:testClasses')
and it worked great. Unfortunately, when I tried to do the same thing for the application module that also has a dependency on the common module tests, it wouldn't work. It fails with:
Build file 'application\build.gradle' line: 103
A problem occurred evaluating project ':application'.
Could not find property 'sourceSets' on project ':common'
After googling a bit I also tried
project.evaluationDependsOn(':common')
testCompile files(project(':common').sourceSets.test.output.classesDir)
But fails with another exception:
Project application: Only Jar-type local dependencies are supported. Cannot handle: common\build\classes\test
Any ideas on how to fix this?
There's a couple of approaches solving the problem of importing test classes in this article. https://softnoise.wordpress.com/2014/09/07/gradle-sub-project-test-dependencies-in-multi-project-builds/ The one I used is:
code in shared module:
task jarTest (type: Jar) {
from sourceSets.test.output
classifier = 'test'
}
configurations {
testOutput
}
artifacts {
testOutput jarTest
}
code in module depending on the shared module:
dependencies{
testCompile project(path: ':common', configuration: 'testOutput')
}
And there seems to be a plugin for it as well! https://plugins.gradle.org/plugin/com.github.hauner.jarTest/1.0
Following the approach from sakis, this should be the configuration you need to get the tests available from another project in the Android platform (done for debug variant).
Shared module:
task jarTests(type: Jar, dependsOn: "assembleDebugUnitTest") {
classifier = 'tests'
from "$buildDir/intermediates/classes/test/debug"
}
configurations {
unitTestArtifact
}
artifacts {
unitTestArtifact jarTests
}
Your module:
dependencies {
testCompile project(path: ":libName", configuration: "unitTestArtifact")
}
The solution mentioned by droidpl for Android + Kotlin looks like this:
task jarTests(type: Jar, dependsOn: "assembleDebugUnitTest") {
getArchiveClassifier().set('tests')
from "$buildDir/tmp/kotlin-classes/debugUnitTest"
}
configurations {
unitTestArtifact
}
artifacts {
unitTestArtifact jarTests
}
Gradle for project that is going to use dependencies:
testImplementation project(path: ':shared', configuration: 'unitTestArtifact')
I know it's kinda an old question but the solution mentioned in the following blog solves the problem very nicely and is not a sort of hack or a temporary workaround:
Shared test sources in Gradle multi-module project
It works something like this:
// in your module's build.gradle file that needs tests from another module
dependencies {
testCompile project(path: ':path.to.project', configuration: 'test')
}
Also you should note that in the very last paragraph he mentioned that you need to enable Create separate module per source set in IntelliJ settings. But it works fine without using that option too. Probably due to changes in the recent IntelliJ versions.
EDIT: IntelliJ recognizes this fine as of 2020.x versions.
I think you could use gradles java test fixtures. This will automatically create a testFixtures source set, in which you can write your test that you want to reuse.
Test fixtures are configured so that:
they can see the main source set classes
test sources can see the test fixtures classes
For example, if you have some class in common module:
public class CommonDto {
private final Long id;
private final String name;
// getters/setters and other methods ...
}
Then in the common module, you could write into src/testFixtures/java following utils:
public class Utils {
private static final CommonDto A = new CommonDto(1, "A");
private static final CommonDto B = new CommonDto(2, "B");
public static CommonDto a() { return A; }
public static CommonDto b() { return B; }
}
Then in you other modules you could add this to reuse Utils class
dependencies {
// other dependencies ...
testImplementation(testFixtures(project(":common")))
}
All of this is better explained in the documentation that I provided initially. There are some nuances that you need to take into account until you create this not to leak test classes into production.

Instrumented Tests in Android Studio

I have been trying to run simple instrumented tests in Android Studio, without any success.
I followed the guide for Unit Tests and it works fine. Now, I would like to tests components which are difficult to mock.
When I follow the guide on instrumented tests, I end up with dependency errors.
What I did:
Install the Android Testing Support Library (Android Support Repository, rev 17).
Create a directory androidTest in src. Add Java folder + package ending with "test".
Add a simple Test class
#RunWith(AndroidJUnit4.class)
public class ServerRequestInstrumentationTest {
#Test
public void test(){
LogC.d("Here we go testing !");
}
}
Add a simple TestSuit.
#RunWith(Suite.class)
#Suite.SuiteClasses({ServerRequestInstrumentationTest.class})
public class TestSuit {
public TestSuit(){}
}
Modify my gradle file to add dependencies.
apply plugin: 'com.android.application'
android {
compileSdkVersion 22
buildToolsVersion "22.0.1"
defaultConfig {
applicationId "com.mydomain.app"
minSdkVersion 9
targetSdkVersion 22
versionCode 28
versionName "2.0.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_7
targetCompatibility JavaVersion.VERSION_1_7
}
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
lintOptions {
disable 'MissingTranslation'
}
}
}
sourceSets { main { java.srcDirs = ['src/main/java'] } }
}
dependencies {
compile 'com.android.support:support-v4:22.2.0'
compile 'com.android.support:appcompat-v7:22.2.0'
wearApp project(':wear')
compile project(':moreapps')
compile project(':lib_repair')
compile project(':bugreport')
//testCompile 'junit:junit:4.12'
testCompile 'org.mockito:mockito-core:1.10.19'
androidTestCompile 'junit:junit:4.12'
androidTestCompile 'org.hamcrest:hamcrest-library:1.1'
androidTestCompile 'com.android.support.test:runner:0.3'
androidTestCompile 'com.android.support.test:rules:0.3'
}
I just added the line androidTestCompile 'junit:junit:4.12', otherwise the annotation #RunWith(AndroidJUnit4.class) wasn't recognized.
Now when I launch the test, I get one Gradle build error.
Error:Execution failed for task ':app:dexDebugAndroidTest'.
com.android.ide.common.process.ProcessException: org.gradle.process.internal.ExecException: Process 'command
'/usr/lib/jvm/jdkoracle/bin/java'' finished with non-zero exit value 2
Any suggestion ? Did I miss something about the testing library ?
Thank you
Okay, finally got it working.
After a little search, I found out that the Gradle console output an error :
AGPBI: {"kind":"simple","text":"UNEXPECTED TOP-LEVEL EXCEPTION:","sources":[{}]}
AGPBI: {"kind":"simple","text":"com.android.dex.DexException: Multiple dex files define Lorg/hamcrest/TypeSafeMatcher;","sources":[{}]}
After I changed one line in my gradle build, Gradle built the project successfuly and I was able to run the simple instrumented test.
Line to change:
androidTestCompile 'org.hamcrest:hamcrest-library:1.1'
to
testCompile 'org.hamcrest:hamcrest-library:1.1'
I don't know why Gradle complains in one case and not the other though...
Instrumentation tests are different to Unit Tests. You have to extend your test classes by specific classes. For more information about that take a look at Android Testing Fundamentals. Also you do not need JUnit for Instrumentaion tests.
Furthermore you have to switch your build variants from Unit Tests to Android Instrumentation Tests, as described here Unit testing in android studio
EXAMPLE:
Here an example for an instrumentaion test in android:
public class ExampleITest extends AndroidTestCase {
#Override
public void setUp() throws Exception {
super.setUp();
InputStream is = getContext().getAssets().open("test.xml");
XmlParser parser = new XmlParser(getContext());
parser.parse(is);
...
}
#MediumTest
public void testSomething() throws Exception {
// test some data your parser extracted from the xml file
...
}
}
As you can see, you can access context, etc.
For this test no specific dependencies are necessary in the gradle file.
I haven't heard about Instrumantation tests just with annotions. maybe i should look it up on the web ;)
Althought #Gordark's answer will not throw any error It's not a proper solution if you want to use Hamcrest in your instrumentation tests, it will work just for your local JVM tests.
I found that using 1.3 version of hamcrest-library actually worked, just replace
androidTestCompile 'org.hamcrest:hamcrest-library:1.1'
with
androidTestCompile 'org.hamcrest:hamcrest-library:1.3'
And it should work. I think it's something about conflicting versions of junit and hamcrest. I guess hamcrest 1.1 depends on a version of junit bellow 4.12, and hamcrest 1.3 depends on junit v4.12
Your answer contains a hint to the problem. You state there that Gradle gives an error. This is because one of the other dependencies for androidTestCompile depends on hamcrest. This is called a transitive dependency. It also means that you can completely remove your explicit requirement for hamcrest. Your change adds hamcrest as a dependency for testCompile which is used for unit tests run locally on your development machine rather than on an Android device or emulator. If you aren't making unit tests you don't need this. Even when you do start writing unit tests, you probably don't need an explicit dependency on hamcrest.

Categories

Resources