tutorial test not medium instrumented found example developers activitytestrule android unit-testing user-interface android-espresso

test - Espresso de Android: no se puede resolver el símbolo AndroidJUnit4.class



test ui android (8)

Es probable que tenga varios tipos de compilación, el proyecto de Android predeterminado cree dos tipos de compilación (depuración / lanzamiento), cambie la variante de compilación para depurar o establezca el valor como se muestra a continuación

http://tools.android.com/tech-docs/new-build-system/user-guide#TOC-Testing

Currently only one Build Type is tested. By default it is the debug Build Type, but this can be reconfigured with: android { ... testBuildType "staging" }

Estoy tratando de crear una prueba de Espresso UI dentro del nuevo proyecto de Android pero enfrenté el siguiente problema.

Si intentara crear una clase de prueba vacía:

import android.content.Intent; import android.support.test.rule.ActivityTestRule; import android.support.test.runner.AndroidJUnit4; import android.test.ActivityInstrumentationTestCase2; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import static android.support.test.espresso.Espresso.onView; import static android.support.test.espresso.assertion.ViewAssertions.matches; import static android.support.test.espresso.matcher.ViewMatchers.withId; import static android.support.test.espresso.matcher.ViewMatchers.withText; @RunWith(AndroidJUnit4.class) public class LoginActivityTest extends ActivityInstrumentationTestCase2<LoginActivity> { }

Siempre recibo este mensaje de error:

cannot resolve symbol AndroidJUnit4.class

Y casi todas las bibliotecas importadas están marcadas como no utilizadas.

El archivo build.gradle contiene lo siguiente:

apply plugin: ''com.android.application'' android { compileSdkVersion 23 buildToolsVersion "23.0.0" defaultConfig { applicationId "com.some.thing.xxx" minSdkVersion 14 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'' } } lintOptions { abortOnError false } packagingOptions { exclude ''LICENSE.txt'' } } repositories { mavenCentral() maven { url "https://oss.sonatype.org/content/repositories/snapshots/" } maven { url "https://jitpack.io" } } dependencies { compile fileTree(dir: ''libs'', include: [''*.jar'']) compile ''com.android.support:appcompat-v7:23.0.0'' compile ''com.google.android.gms:play-services:7.8.0'' compile ''com.mcxiaoke.volley:library:1.0.18'' compile ''com.orhanobut:logger:1.11'' // App dependencies compile ''com.android.support:support-annotations:23.0.0'' // TESTING DEPENDENCIES androidTestCompile ''com.android.support.test:runner:0.3'' // Set this dependency to use JUnit 4 rules androidTestCompile ''com.android.support.test:rules:0.3'' // Set this dependency to build and run Espresso tests androidTestCompile ''com.android.support.test.espresso:espresso-core:2.2'' // add this for intent mocking support androidTestCompile ''com.android.support.test.espresso:espresso-intents:2.2'' // add this for webview testing support androidTestCompile ''com.android.support.test.espresso:espresso-web:2.2'' // Set this dependency to build and run UI Automator tests androidTestCompile ''com.android.support.test.uiautomator:uiautomator-v18:2.1.1'' androidTestCompile ''com.android.support.test.espresso:espresso-contrib:2.2'' }

Si pongo estos ajustes en mi otro proyecto de prueba, funciona, ¿entonces no sé qué puede estar mal?

He seguido este tutorial: "

http://www.vogella.com/tutorials/AndroidTestingEspresso/article.html

Y he intentado resolverlo siguiendo la pregunta SO: No se puede resolver el símbolo ''AndroidJUnit4''

Pero sin la suerte.

Muchas gracias por cualquier consejo.


La razón por la que recibe ese mensaje de error puede deberse a que la carpeta donde reside la prueba no coincide con la especificación. La carpeta debe ser src / androidTest / java .

Echa un vistazo a este artículo que dice ...

Ejecutar pruebas unitarias instrumentadas Para ejecutar sus pruebas instrumentadas, siga estos pasos:

Asegúrese de que su proyecto esté sincronizado con Gradle haciendo clic en Sincronizar proyecto en la barra de herramientas. Ejecute su prueba de una de las siguientes maneras: Para ejecutar una sola prueba, abra la ventana Proyecto y luego haga clic con el botón derecho en una prueba y haga clic en Ejecutar Para probar todos los métodos en una clase, haga clic derecho en una clase o método en el archivo de prueba y haga clic en Ejecutar. Para ejecutar todas las pruebas en un directorio, haga clic derecho en el directorio y seleccione Ejecutar pruebas. Android Plugin for Gradle compila el código de prueba instrumentado ubicado en el directorio predeterminado (src / androidTest / java /), crea un APK de prueba y un APK de producción, instala ambos APKs en el dispositivo o emulador conectado y ejecuta las pruebas. Luego, Android Studio muestra los resultados de la ejecución de la prueba instrumentada en la ventana Ejecutar.

Por lo tanto, amigos, para la prueba de instrumentación, la carpeta debe ser (no olvide el caso)

src / prueba de android / java

y para las pruebas locales la carpeta debe ser

src / test / java

Luego puede tener su (s) carpeta (s) de paquetes para que coincida con su paquete de aplicaciones

Espero, esto ayuda a la comunidad!


Lo resolví cambiando la constante.

minSdkVersion

a la versión 18 en el archivo build.gradle .

Siguiendo gradle.file está trabajando:

apply plugin: ''com.android.application'' android { compileSdkVersion 23 buildToolsVersion "23.0.0" defaultConfig { applicationId "com.something.xxx" minSdkVersion 18 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'' } } lintOptions { abortOnError false } packagingOptions { exclude ''LICENSE.txt'' } } repositories { mavenCentral() maven { url "https://oss.sonatype.org/content/repositories/snapshots/" } maven { url "https://jitpack.io" } } dependencies { compile fileTree(dir: ''libs'', include: [''*.jar'']) compile ''com.android.support:appcompat-v7:23.0.0'' compile ''com.google.android.gms:play-services:7.8.0'' compile ''com.mcxiaoke.volley:library:1.0.18'' compile ''com.orhanobut:logger:1.11'' // TESTING DEPENDENCIES androidTestCompile ''com.android.support:support-annotations:23.0.0'' androidTestCompile ''com.android.support.test:runner:0.3'' // Set this dependency to use JUnit 4 rules androidTestCompile ''com.android.support.test:rules:0.3'' // Set this dependency to build and run Espresso tests androidTestCompile ''com.android.support.test.espresso:espresso-core:2.2'' // add this for intent mocking support androidTestCompile ''com.android.support.test.espresso:espresso-intents:2.2'' // add this for webview testing support androidTestCompile ''com.android.support.test.espresso:espresso-web:2.2'' // Set this dependency to build and run UI Automator tests androidTestCompile ''com.android.support.test.uiautomator:uiautomator-v18:2.1.1'' androidTestCompile ''com.android.support.test.espresso:espresso-contrib:2.2'' }


Lo resolví importando manualmente lo siguiente, pensé que debería importarse automáticamente pero no fue así:

import static android.support.test.espresso.Espresso.onView; import static android.support.test.espresso.action.ViewActions.click; import static android.support.test.espresso.action.ViewActions.closeSoftKeyboard; import static android.support.test.espresso.action.ViewActions.typeText; import static android.support.test.espresso.assertion.ViewAssertions.matches; import static android.support.test.espresso.matcher.ViewMatchers.withId; import static android.support.test.espresso.matcher.ViewMatchers.withText;


Puede referirse a esta respuesta .

"Cometí el error de poner las clases de prueba en src / test. Después de moverlas a src / androidTest / java / ... la dependencia se resolvió. Tal vez este sea su problema también".


Según los cambios de grado anteriores dados:

androidTestCompile ''com.android.support.test:runner:0.3''

necesitas cambiar a

androidTestCompile(''com.android.support.test:runner:0.3'') { exclude group: ''com.android.support'', module: ''support-annotations'' }

y para mí no funcionó incluso con el cambio anterior, así que lo que noté fue que me faltaba la siguiente inclusión:

androidTestCompile ''com.android.support.test.uiautomator:uiautomator-v18:2.1.1''

y funcionó bien para mí.

El build.gradle completo se puede encontrar a continuación:

apply plugin: ''com.android.application'' android { compileSdkVersion 23 buildToolsVersion "21.1.2" lintOptions { // IMPORTANT: We are disabling this rule to avoid build errors on PrettyTime. Although //pretty time references an InvalidPackage it does not do it in the code sections we use //given how easy this library is to use I would prefer not to replace it with something //like Joda-Time which is overkill for such a small section of the app. disable ''InvalidPackage'' } packagingOptions { exclude ''LICENSE.txt'' } defaultConfig { applicationId "co.test.dialer" minSdkVersion 18 targetSdkVersion 22 versionCode 15 versionName "0.6.15." renderscriptTargetApi 22 renderscriptSupportModeEnabled true testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner" } signingConfigs { production { storeFile file("keystore.jks") storePassword "hello" keyAlias "production" keyPassword "android" } debug { storeFile file("keystore.jks") storePassword "hello" keyAlias "debug" keyPassword "android" } } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile(''proguard-android.txt''), ''proguard-rules.pro'' signingConfig signingConfigs.production } debug { minifyEnabled false debuggable true applicationIdSuffix ".debug" signingConfig signingConfigs.debug } internal_test { minifyEnabled false debuggable true applicationIdSuffix ".test" signingConfig signingConfigs.debug } } } dependencies { compile fileTree(dir: ''libs'', include: [''*.jar'']) compile ''com.android.support:appcompat-v7:23.0.1'' compile ''com.android.support:support-v13:23.0.1'' compile ''com.android.support:cardview-v7:23.0.1'' compile ''com.android.support:design:23.0.1'' compile ''com.android.support:recyclerview-v7:23.0.1'' compile ''com.google.android.gms:play-services-gcm:8.1.0'' compile ''com.jakewharton:butterknife:6.1.0'' compile ''com.afollestad:material-dialogs:0.7.8.0'' compile ''com.googlecode.libphonenumber:libphonenumber:3.1'' compile ''com.mcxiaoke.volley:library:1.0.15'' compile ''squizbit.com.jsonobjectified:jetjson:1.0.3@aar'' compile ''com.google.android.gms:play-services-analytics:8.1.0'' releaseCompile ''co.test.dialersdk:dialersdk:1.0.8@aar''; debugCompile ''co.test.dialersdk:dialersdk-debug:1.0.8@aar''; internal_testCompile ''co.test.dialersdk:dialersdk-internal_test:1.0.8@aar''; androidTestCompile(''com.android.support.test:runner:0.3'') { exclude group: ''com.android.support'', module: ''support-annotations'' } androidTestCompile(''com.android.support.test:rules:0.3'') { exclude group: ''com.android.support'', module: ''support-annotations'' } androidTestCompile(''com.android.support.test.espresso:espresso-core:2.2'') { exclude group: ''com.android.support'', module: ''support-annotations'' } androidTestCompile(''com.android.support.test.espresso:espresso-intents:2.2'') { exclude group: ''com.android.support'', module: ''support-annotations'' } androidTestCompile(''com.android.support.test.espresso:espresso-contrib:2.2'') { exclude group: ''com.android.support'', module: ''support-annotations'' exclude group: ''com.android.support'', module: ''appcompat'' exclude group: ''com.android.support'', module: ''support-v4'' exclude module: ''recyclerview-v7'' } androidTestCompile(''com.android.support.test.espresso:espresso-web:2.2'') { exclude group: ''com.android.support'', module: ''support-annotations'' } androidTestCompile ''com.android.support.test.uiautomator:uiautomator-v18:2.1.1'' }

Espero que esto seguramente ayude a alguien, ya que he luchado durante medio día para solucionarlo incluso después de seguir los pasos completos del tutorial de Vogella.


También probé el mismo tutorial de vogella y tuve muchos problemas. Uno de los primeros problemas con los que me topé fue un choque de dependencias entre las versiones de anotación de las bibliotecas v23 y las libres de espresso.

Luego encontré otro tutorial actualizado recientemente de Roger Hu " UI Testting with Espresso ". Noté un comentario que Espresso no está apoyando a Marshmallow todavía.

Las dependencias se agregaron de la siguiente manera:

androidTestCompile(''com.android.support.test.espresso:espresso-core:2.2'') { // Necessary if your app targets Marshmallow (since Espresso // hasn''t moved to Marshmallow yet) exclude group: ''com.android.support'', module: ''support-annotations'' } androidTestCompile(''com.android.support.test:runner:0.3'') { // Necessary if your app targets Marshmallow (since the test runner // hasn''t moved to Marshmallow yet) exclude group: ''com.android.support'', module: ''support-annotations'' }

Esto resolvió mi conflicto de dependencia y no vi que ocurriera el resto de los problemas.