Android prob with AndroidJUnitRunner giving 'java.lang.ClassNotFoundException' - android

I am new in Instrumentation testing. I am trying basic testing with AndroidJUnitRunner. Here is my gradle:
apply plugin: 'com.android.application'
android {
compileSdkVersion 24
buildToolsVersion "25.0.0"
defaultConfig {
applicationId "com.kaushik.mycart.ui"
minSdkVersion 15
targetSdkVersion 24
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
jackOptions.enabled true
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
exclude group: 'com.android.support', module: 'support-annotations'
})
..........................
..........................
testCompile 'junit:junit:4.12'
testCompile 'org.mockito:mockito-core:1.10.19'
androidTestCompile 'org.hamcrest:hamcrest-library:1.3'
}
Then I added a class named 'ProductListActivityTest' to test with AndroidJunitRunner. It is below:
package com.kaushik.myredmart.ui;
// all includes
#RunWith(AndroidJUnit4.class)
public class ProductListActivityTest {
#Rule
public ActivityTestRule<ProductListActivity> rule = new ActivityTestRule<>(ProductListActivity.class);
#Test
public void ensureListViewIsPresent() throws Exception {
ProductListActivity activity = rule.getActivity();
View viewByIdw = activity.findViewById(R.id.productListView);
assertThat(viewByIdw,notNullValue());
assertThat(viewByIdw, instanceOf(RecyclerView.class));
RecyclerView productListView = (RecyclerView) viewByIdw;
RecyclerView.Adapter adapter = productRecyclerView.getAdapter();
assertThat(adapter, instanceOf(ProductAdapter.class));
}
}
I have added no other file in 'androidTest'. I like to also mention that there is Application class file in my source code. Now every time I try to run the test, it is giving following error:
Started running tests
Test running failed: Instrumentation run failed due to 'java.lang.ClassNotFoundException'
Empty test suite.
Can anyone help me identifying the problem in my test code?

How are you running your tests?
If you are doing it from Android Studio:
Open Run menu -> Edit Configurations
Add a new Android Tests configuration
Choose a module
Add a specific instrumentation runner:
android.support.test.runner.AndroidJUnitRunner
From command-line via Gradle:
./gradlew connectedAndroidTest

I solved the problem. It is due to difference of Package names. I set all package name uniform and run again. It works. Thank you all for helping.

Related

Test code not being compiled and treated as non-test

I have some Android instrumentation tests with a custom test runner that all seemed to work fine until at some point after I upgraded to Android Studio 2.1, bumped up some library versions, and did some other things over time. Now, my tests don't run anymore with the dreaded Unable to find instrumentation info for: ComponentInfo{} that has been asked about on StackOverflow a million times already.
Upon further investigation, it seems like Android Studio simply doesn't compile my test code, which then means its code is never included, so it can't find the ComponentInfo for the test runner. I verified that by adding compile errors in my test code, which never cause any issues when I try to run a test.
Furthermore, the test code seems to be treated like non-test code in the syntax highlighter? As an example, the test runner imports android.support.test.runner.AndroidJUnitRunner, but runner is highlighted in red as if that library is missing (but it's in the gradle file as androidTestCompile). If I change that to compile, the syntax highlighter is happy. However, the test code shows up in the project view in yellow, like test code would.
I'm not sure what determines what Android Studio compiles for a test. The setup is straightforward. My file hierarchy is
app
+--src
+ +--main
+ | +--java
+ | +--com/package/files
+ |
+ +--androidTest
+ +--java
+ +--com/package/files
In other words, there's app/src/main/java/com/... and app/src/androidTest/java/com.... Both the main app and the tests use the same package.
build.gradle (relevant parts):
apply plugin: 'com.android.application'
android {
compileSdkVersion 'Google Inc.:Google APIs:23'
buildToolsVersion '24.0.0 rc3'
defaultConfig {
multiDexEnabled = true
applicationId 'com.package'
minSdkVersion 10
targetSdkVersion 23
versionCode 2
versionName '0.8a'
signingConfig signingConfigs.release
testInstrumentationRunner 'com.package.TestRunner'
}
buildTypes {
release {
signingConfig signingConfigs.release
}
debug {
signingConfig signingConfigs.release
}
}
productFlavors {
}
dexOptions {
javaMaxHeapSize "4g"
}
packagingOptions {
exclude 'META-INF/LICENSE'
exclude 'META-INF/LICENSE-FIREBASE.txt'
exclude 'META-INF/NOTICE'
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_7
targetCompatibility JavaVersion.VERSION_1_7
}
lintOptions {
checkReleaseBuilds true
abortOnError true
}
}
dependencies {
compile fileTree(include: ['*.jar'], dir: 'libs')
androidTestCompile 'com.android.support.test:runner:0.5'
androidTestCompile 'com.android.support.test:rules:0.5'
androidTestCompile 'com.android.support.test.espresso:espresso-core:2.2.1'
androidTestCompile 'com.android.support.test.espresso:espresso-intents:2.2'
androidTestCompile 'org.hamcrest:hamcrest-library:1.3'
androidTestCompile 'com.android.support:support-annotations:23.1.1'
compile 'com.android.support:appcompat-v7:23.1.1'
compile 'com.android.support:support-v4:23.1.1'
[...]
}
apply plugin: 'com.google.gms.google-services'
The run/debug configuration for the test is straightforward as well - it's an Android Test, the instrumentation runner is com.package.TestRunner. I tried cleaning/rebuilding many times.
The answer is so embarrassing that I shouldn't post it.
The "Build Variant" for all my modules was set to "Release", so none of the test stuff was compiled. Setting it to "Debug" took care of the problem. Would be nice if Android Studio was a bit more vocal about it, like warning about running tests while using the release shards.

Android Studio Junit tests package org.junit does not exist

I'm trying to implement a test class in Android Studio to make some test on a DBAdapter. Since I need to run the test on my mobile phone in order to use the database, I have created an Instrumentation Unit Test (cause I've tried to do it just with a Unit test but I need to use the database and so, and those are only run locally).
The problem is that when I try to run the test class, using my mobile phone as running device, the compiler throws the following error:
error: package org.junit does not exist
I've been looking for a solutione, but I found none.
This is my test class (just the skeleton):
import org.junit.Test;
import android.support.test.runner.AndroidJUnit4;
import static org.junit.Assert.*;
public class DbAdapterTest {
#Test
public void testCreateSeries() throws Exception {
}
}
And this one is the build.gradle script:
apply plugin: 'com.android.application'
android {
compileSdkVersion 23
buildToolsVersion "23.0.2"
defaultConfig {
applicationId "com.w2w.whattowatch"
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'
}
}
testOptions {
unitTests.returnDefaultValues = true
}
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile 'com.android.support:appcompat-v7:23.1.1'
compile 'com.android.support:design:23.1.1'
testCompile 'junit:junit:4.12'
testCompile "org.mockito:mockito-core:1.9.5"
}
I also have another issue. As you can see, I also imported this:
import android.support.test.runner.AndroidJUnit4;
But, even before running, it says of "runner" that "cannot resolve the symbol". I've added the TestInstrumentationRunner on build.gradle, but still not working.
OK, I solve it so, this is the solution that worked for me.
I didn't have this dependences, so I add them to the build.gradle script:
androidTestCompile 'com.android.support:support-annotations:23.1.1'
androidTestCompile 'com.android.support.test:runner:0.4.1'
androidTestCompile 'com.android.support.test:rules:0.4.1'

Android Studio Espresso Empty Test Suite

When I run my test method that uses Espresso, it prompts me to choose an emulator, and I pick my existing emulator with my application already started. The emulator subsequently automatically reboots my application, and then displays that that the test suite is empty.
My espresso test case is located in the androidTest folder of the same module as the activity I'm trying to test. I wrote a simple "isDisplayed()" type of a test and right clicked the method and clicked run. I've taken a look at the other questions on Stack Overflow and other resources, but I can't figure out what is causing this problem. The logcat displays nothing and when I tried putting Log.d("debug", "hello hello") in the test method (shown below), nothing shows up in the logcat, nor does anything display when I try putting a System.out.println("hello") in the test method. It seems that although I run the method, none of my code is being run!
Below is some of my build.grade.
apply plugin: 'com.android.application'
android {
compileSdkVersion 17
buildToolsVersion "21.1.2"
defaultConfig {
applicationId "x"
minSdkVersion 17
targetSdkVersion 17
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
packagingOptions {
exclude 'META-INF/LICENSE.txt'
exclude 'META-INF/NOTICE.txt'
exclude 'LICENSE.txt'
}
}
configurations.all {
resolutionStrategy.force 'com.android.support:support-annotations:22.2.0'
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
androidTestCompile 'com.android.support.test:rules:0.3'
androidTestCompile 'com.android.support.test:runner:0.3'
androidTestCompile 'com.android.support.test.espresso:espresso-core:2.2'
}
Here is the test case that I'm trying to run.
#RunWith(AndroidJUnit4.class)
public class EspressoTest1 extends ActivityInstrumentationTestCase2<P1>{
private P1 mActivity;
public EspressoTest1() {
super(P1.class);
}
public void setUp() throws Exception {
super.setUp();
injectInstrumentation(InstrumentationRegistry.getInstrumentation());
mActivity = getActivity();
}
public void Happy_test() {
onView(withId(R.id.Btn)).check(matches(isDisplayed()));
}
}
And this is the test run configuration.
Your test is missing #Test annotation. So as your setup method is missing #Before
Maybe this will help other people (like Igor Ganapolsky).
When you are using annotations from Espresso library you have to add testInstrumenatationRunner to your gradle file. Missing this line occurs the same error message "Empty test suite"
defaultConfig {
applicationId "com.test.app"
minSdkVersion 16
targetSdkVersion 24
versionCode 1
versionName "1.0.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}

Empty Jacoco report for Android Espresso

I am trying to get code coverage for my Android project using Espresso tests. However, Jacoco is giving me back a report saying that I don't cover anything. I made a demo app to highlight my problem and that is here.
If you don't want to go to Github to look at the project, here is the build.gradle file:
apply plugin: 'com.android.application'
apply plugin: 'jacoco'
android {
compileSdkVersion 22
buildToolsVersion "22.0.1"
defaultConfig {
applicationId "ninja.bryansills.jacocotest"
minSdkVersion 16
targetSdkVersion 22
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
packagingOptions {
exclude 'LICENSE.txt'
}
compileOptions {
sourceCompatibility JavaVersion.VERSION_1_7
targetCompatibility JavaVersion.VERSION_1_7
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
debug {
testCoverageEnabled true
}
}
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile 'com.android.support:appcompat-v7:22.1.1'
androidTestCompile 'com.android.support.test:runner:0.2'
androidTestCompile 'com.android.support.test:rules:0.2'
androidTestCompile 'com.android.support.test.espresso:espresso-core:2.1'
}
Based on the issue pointed out by Ligol, here is what worked for me.
Added custom test runner in androidTest
package com.example;
import android.os.Bundle;
import android.support.test.runner.AndroidJUnitRunner;
import android.util.Log;
import java.lang.reflect.Method;
public class AndroidJacocoTestRunner extends AndroidJUnitRunner {
static {
System.setProperty("jacoco-agent.destfile", "/data/data/"+BuildConfig.APPLICATION_ID+"/coverage.ec");
}
#Override
public void finish(int resultCode, Bundle results) {
try {
Class rt = Class.forName("org.jacoco.agent.rt.RT");
Method getAgent = rt.getMethod("getAgent");
Method dump = getAgent.getReturnType().getMethod("dump", boolean.class);
Object agent = getAgent.invoke(null);
dump.invoke(agent, false);
} catch (Throwable e) {
Log.d("JACOCO", e.getMessage());
}
super.finish(resultCode, results);
}
}
Used this test runner in app/build.gradle
android{
...
defaultConfig {
....
testInstrumentationRunner "com.example.AndroidJacocoTestRunner"
}
}
Your problem might be related to this issue.
https://code.google.com/p/android/issues/detail?id=170607
I had the same problem on Samsung device, I did not change anything but changed to HTC device I started getting the coverage.ec Something seems to be fishy with JaCoCo Samsung device.
I advise everyone not to use a Samsung device while generating coverage reports. I tried everything to fix the 0 coverage issue and luckily changed my device to Redmi Note 5 Pro and voila the coverage starts showing.
On doing some research and reading some articles I found Samsung give less freedom to its user to use their products for testing. Though you can do the testing on Samsung devices after rooting them.

Java annotation processing for Android unit testing (w/ Dagger)

I am attempting to set up Android unit tests in Android Studio 1.0 using DI from Dagger version 1.2.2.
Whenever I run my tests and I attempt to instantiate an ObjectGraph with my test module, I get the following error/stacktrace:
java.lang.IllegalStateException: Module adapter for class java.util.Arrays$ArrayList could not be loaded. Please ensure that code generation was run for this module.
at dagger.internal.FailoverLoader$1.create(FailoverLoader.java:45)
at dagger.internal.FailoverLoader$1.create(FailoverLoader.java:40)
at dagger.internal.Memoizer.get(Memoizer.java:56)
at dagger.internal.FailoverLoader.getModuleAdapter(FailoverLoader.java:57)
at dagger.internal.Modules.loadModules(Modules.java:43)
at dagger.ObjectGraph$DaggerObjectGraph.makeGraph(ObjectGraph.java:174)
at dagger.ObjectGraph$DaggerObjectGraph.access$000(ObjectGraph.java:138)
at dagger.ObjectGraph.create(ObjectGraph.java:129)
at com.company.app.HttpRequestManagerTest.setUp(HttpRequestManagerTest.java:35)
at android.test.AndroidTestRunner.runTest(AndroidTestRunner.java:191)
at android.test.AndroidTestRunner.runTest(AndroidTestRunner.java:176)
at android.test.InstrumentationTestRunner.onStart(InstrumentationTestRunner.java:555)
at android.app.Instrumentation$InstrumentationThread.run(Instrumentation.java:1837)
Here is the breaking code (# ObjectGraph.create):
#Override
public void setUp() throws Exception {
super.setUp();
setContext(new MockContext());
mObjectGraph = ObjectGraph.create(Arrays.asList(new TestModule()));
mObjectGraph.inject(this);
}
Diving deeper, here is the TestModule:
package com.company.app.provider;
import dagger.Module;
#Module(
overrides = true,
library = true
)
public class TestModule {
}
It seems as though it's indicating that Java annotation processing is not active, but I don't think that's the case as I'm using other annotations such as #Override in my code without issues. I'm wondering if somehow the Dagger annotation processor is not being applied to the test build. Here is my build.gradle for what it's worth:
apply plugin: 'com.android.application'
android {
compileSdkVersion 21
buildToolsVersion "21.1.1"
defaultConfig {
applicationId "com.company.app"
minSdkVersion 14
targetSdkVersion 21
versionCode 1
versionName "1.0"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}
packagingOptions {
pickFirst 'META-INF/services/javax.annotation.processing.Processor'
}
}
ext {
daggerVersion = '1.2.2'
mockitoVersion = '2.0.3-beta'
powerMockVersion = '1.5.4'
}
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
compile 'com.android.support:appcompat-v7:21.0.3'
compile 'com.android.support:support-v13:21.0.0'
compile 'io.realm:realm-android:0.77.0'
compile 'com.squareup.okhttp:okhttp:2.2.0'
compile 'com.jakewharton:butterknife:6.0.0'
compile "com.squareup.dagger:dagger:$daggerVersion"
provided "com.squareup.dagger:dagger-compiler:$daggerVersion"
androidTestCompile "org.mockito:mockito-core:$mockitoVersion"
}
The only fishy thing I could find here was the pickFirst 'META-INF/services/javax.annotation.processing.Processor', but that is necessary to overcome a known Butterknife issue.
Any input is greatly appreciated, thanks!
ObjectGraph.create(Arrays.asList(new TestModule()));
ObjectGraph.create is a varargs method. It does not take a List. You can either list out your modules as individual arguments or pass an Object[].
ObjectGraph.create(new TestModule());

Categories

Resources