Android: базовый тест с эспрессо

Я пытаюсь добавить базовый тест эспрессо в свое приложение для Android. Мой тестовый файл (расположенный в папке androidTest / java) был создан функцией «запись теста эспрессо» и выглядит следующим образом:

package info.my_xxxx.activities;


import android.support.test.espresso.ViewInteraction;
import android.support.test.rule.ActivityTestRule;
import android.support.test.runner.AndroidJUnit4;
import android.test.suitebuilder.annotation.LargeTest;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;

import org.hamcrest.Description;
import org.hamcrest.Matcher;
import org.hamcrest.TypeSafeMatcher;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;

import info.my_xxxx.R;

import static android.support.test.espresso.Espresso.onView;
import static android.support.test.espresso.action.ViewActions.click;
import static android.support.test.espresso.assertion.ViewAssertions.matches;
import static android.support.test.espresso.matcher.ViewMatchers.isDisplayed;
import static android.support.test.espresso.matcher.ViewMatchers.withId;
import static android.support.test.espresso.matcher.ViewMatchers.withText;
import static org.hamcrest.Matchers.allOf;

@LargeTest
@RunWith(AndroidJUnit4.class)
public class AdviceDisplay2 {

    @Rule
    public IntentsTestRule<SplashActivity> mActivityTestRule = new IntentsTestRule<>(SplashActivity.class);

    @Test
    public void adviceDisplay2() {
        // Added a sleep statement to match the app's execution delay.
        // The recommended way to handle such scenarios is to use Espresso idling resources:
        // https://google.github.io/android-testing-support-library/docs/espresso/idling-resource/index.html
        try {
            Thread.sleep(10000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        ViewInteraction appCompatImageView = onView(
                allOf(withId(R.id.third_button),
                        childAtPosition(
                                allOf(withId(R.id.linear_layout),
                                        childAtPosition(
                                                withId(R.id.bottom_button),
                                                0)),
                                2),
                        isDisplayed()));
        appCompatImageView.perform(click());

        ViewInteraction textView = onView(
                allOf(withId(R.id.advice),
                        childAtPosition(
                                allOf(withId(R.id.RelativeLayout01),
                                        childAtPosition(
                                                withId(android.R.id.content),
                                                0)),
                                1),
                        isDisplayed()));
        textView.check(matches(isDisplayed()));

    }

    private static Matcher<View> childAtPosition(
            final Matcher<View> parentMatcher, final int position) {

        return new TypeSafeMatcher<View>() {
            @Override
            public void describeTo(Description description) {
                description.appendText("Child at position " + position + " in parent ");
                parentMatcher.describeTo(description);
            }

            @Override
            public boolean matchesSafely(View view) {
                ViewParent parent = view.getParent();
                return parent instanceof ViewGroup && parentMatcher.matches(parent)
                        && view.equals(((ViewGroup) parent).getChildAt(position));
            }
        };
    }
}

Как видите, это просто щелчок по представлению и проверка, существует ли представление или нет ... Мой файл gradle (уровень модуля):

buildscript {
    repositories {
        maven { url 'https://maven.fabric.io/public' }
    }

    dependencies {
        classpath 'io.fabric.tools:gradle:1.+'
    }
}
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
apply plugin: 'io.fabric'

repositories {
    maven { url 'https://maven.fabric.io/public' }
    google()
    mavenCentral()
}

android {

    dexOptions {
        javaMaxHeapSize "4g"
    }

    compileSdkVersion 26
    buildToolsVersion '26.0.2'

    defaultConfig {
        applicationId "info.xxx"
        minSdkVersion 16
        targetSdkVersion 26
        multiDexEnabled true
        testInstrumentationRunner 'android.support.test.runner.AndroidJUnitRunner'

    }

    signingConfigs{
        release {
            v2SigningEnabled false
        }
    }

    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_7
        targetCompatibility JavaVersion.VERSION_1_7
    }

    buildTypes {
        release {
            debuggable false
            minifyEnabled true
            shrinkResources true
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
        }
    }
}

dependencies {

    implementation  'com.google.android.gms:play-services-analytics:11.8.0'

    implementation 'com.android.support:appcompat-v7:26.1.0'
    implementation 'com.android.support:design:26.1.0'

    implementation 'com.android.support:multidex:1.0.2'
    implementation ('com.squareup:android-times-square:1.7.2@aar'){
        exclude group: 'com.android.support', module: 'mediarouter-v7'
    }

    implementation files('libs/GraphView-3.1.3.jar')
    implementation('com.crashlytics.sdk.android:crashlytics:2.6.8@aar') {
        transitive = true
    }

    // Kotlin related
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jre7:$kotlin_version"
    implementation "org.jetbrains.anko:anko-appcompat-v7-commons:$anko_version"
    implementation "org.jetbrains.anko:anko-design:$anko_version"
    implementation "org.jetbrains.anko:anko-design-coroutines:$anko_version"

    // Required for local unit tests (JUnit 4 framework)
    testImplementation 'junit:junit:4.12'

    //Mockito framework
    testImplementation 'org.mockito:mockito-core:1.10.19'

    // Required for instrumented tests
    androidTestImplementation 'com.android.support:support-annotations:26.+'
    androidTestImplementation ('com.android.support.test:runner:1.0.1'){
        exclude module: 'support-annotations'
    }
    androidTestImplementation ('com.android.support.test.espresso:espresso-core:3.0.1'){
        exclude module: 'support-annotations'
    }

}

Кажется, все зависимости в порядке, но при запуске теста из студии Android через несколько минут я получил это сообщение:

Тесты завершены.

Строка 56:

Спасибо за чтение

appCompatImageView.perform(click());

Сегодня у меня была такая же ошибка, но в моем случае она была связана с управлением версиями библиотек. Я потратил много времени, пытаясь выяснить, как вернуть мои тесты, и одним из ключей к решению моей проблемы было установление для

package info.my_xxxx.activities;


import android.support.test.espresso.ViewInteraction;
import android.support.test.rule.ActivityTestRule;
import android.support.test.runner.AndroidJUnit4;
import android.test.suitebuilder.annotation.LargeTest;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;

import org.hamcrest.Description;
import org.hamcrest.Matcher;
import org.hamcrest.TypeSafeMatcher;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;

import info.my_xxxx.R;

import static android.support.test.espresso.Espresso.onView;
import static android.support.test.espresso.action.ViewActions.click;
import static android.support.test.espresso.assertion.ViewAssertions.matches;
import static android.support.test.espresso.matcher.ViewMatchers.isDisplayed;
import static android.support.test.espresso.matcher.ViewMatchers.withId;
import static android.support.test.espresso.matcher.ViewMatchers.withText;
import static org.hamcrest.Matchers.allOf;

@LargeTest
@RunWith(AndroidJUnit4.class)
public class AdviceDisplay2 {

    @Rule
    public IntentsTestRule<SplashActivity> mActivityTestRule = new IntentsTestRule<>(SplashActivity.class);

    @Test
    public void adviceDisplay2() {
        // Added a sleep statement to match the app's execution delay.
        // The recommended way to handle such scenarios is to use Espresso idling resources:
        // https://google.github.io/android-testing-support-library/docs/espresso/idling-resource/index.html
        try {
            Thread.sleep(10000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        ViewInteraction appCompatImageView = onView(
                allOf(withId(R.id.third_button),
                        childAtPosition(
                                allOf(withId(R.id.linear_layout),
                                        childAtPosition(
                                                withId(R.id.bottom_button),
                                                0)),
                                2),
                        isDisplayed()));
        appCompatImageView.perform(click());

        ViewInteraction textView = onView(
                allOf(withId(R.id.advice),
                        childAtPosition(
                                allOf(withId(R.id.RelativeLayout01),
                                        childAtPosition(
                                                withId(android.R.id.content),
                                                0)),
                                1),
                        isDisplayed()));
        textView.check(matches(isDisplayed()));

    }

    private static Matcher<View> childAtPosition(
            final Matcher<View> parentMatcher, final int position) {

        return new TypeSafeMatcher<View>() {
            @Override
            public void describeTo(Description description) {
                description.appendText("Child at position " + position + " in parent ");
                parentMatcher.describeTo(description);
            }

            @Override
            public boolean matchesSafely(View view) {
                ViewParent parent = view.getParent();
                return parent instanceof ViewGroup && parentMatcher.matches(parent)
                        && view.equals(((ViewGroup) parent).getChildAt(position));
            }
        };
    }
}
,
buildscript {
    repositories {
        maven { url 'https://maven.fabric.io/public' }
    }

    dependencies {
        classpath 'io.fabric.tools:gradle:1.+'
    }
}
apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
apply plugin: 'io.fabric'

repositories {
    maven { url 'https://maven.fabric.io/public' }
    google()
    mavenCentral()
}

android {

    dexOptions {
        javaMaxHeapSize "4g"
    }

    compileSdkVersion 26
    buildToolsVersion '26.0.2'

    defaultConfig {
        applicationId "info.xxx"
        minSdkVersion 16
        targetSdkVersion 26
        multiDexEnabled true
        testInstrumentationRunner 'android.support.test.runner.AndroidJUnitRunner'

    }

    signingConfigs{
        release {
            v2SigningEnabled false
        }
    }

    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_7
        targetCompatibility JavaVersion.VERSION_1_7
    }

    buildTypes {
        release {
            debuggable false
            minifyEnabled true
            shrinkResources true
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.txt'
        }
    }
}

dependencies {

    implementation  'com.google.android.gms:play-services-analytics:11.8.0'

    implementation 'com.android.support:appcompat-v7:26.1.0'
    implementation 'com.android.support:design:26.1.0'

    implementation 'com.android.support:multidex:1.0.2'
    implementation ('com.squareup:android-times-square:1.7.2@aar'){
        exclude group: 'com.android.support', module: 'mediarouter-v7'
    }

    implementation files('libs/GraphView-3.1.3.jar')
    implementation('com.crashlytics.sdk.android:crashlytics:2.6.8@aar') {
        transitive = true
    }

    // Kotlin related
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jre7:$kotlin_version"
    implementation "org.jetbrains.anko:anko-appcompat-v7-commons:$anko_version"
    implementation "org.jetbrains.anko:anko-design:$anko_version"
    implementation "org.jetbrains.anko:anko-design-coroutines:$anko_version"

    // Required for local unit tests (JUnit 4 framework)
    testImplementation 'junit:junit:4.12'

    //Mockito framework
    testImplementation 'org.mockito:mockito-core:1.10.19'

    // Required for instrumented tests
    androidTestImplementation 'com.android.support:support-annotations:26.+'
    androidTestImplementation ('com.android.support.test:runner:1.0.1'){
        exclude module: 'support-annotations'
    }
    androidTestImplementation ('com.android.support.test.espresso:espresso-core:3.0.1'){
        exclude module: 'support-annotations'
    }

}
и appCompatImageView.perform(click()); одной и той же версии.


person johann    schedule 13.01.2018    source источник
comment
Спасибо за ваш ответ. Даже если я изменю buildToolsVersion, он вернет сообщение: Предупреждение: указанная версия Android SDK Build Tools (25.0.2) игнорируется, так как она ниже минимальной поддерживаемой версии (26.0.2) для Android Gradle Plugin 3.0.1. Будут использоваться Android SDK Build Tools 26.0.2. Чтобы подавить это предупреждение, удалите buildToolsVersion '25 .0.2 'из файла build.gradle, так как каждая версия Android Gradle Plugin теперь имеет версию инструментов сборки по умолчанию.   -  person Ahmed    schedule 18.11.2018


Ответы (1)


Итак, не могли бы вы попробовать обновить свой buildToolsVersion '25.2.0' и проверить, работает ли он?

Как вы интегрируете эспрессо в свой проект. Я использовал его зависимость, как и вы, но она не определяла.

person Maychell Fernandes    schedule 13.01.2018
comment
Понятно ... А как насчет того, чтобы поменять остальные на sdk версии 26 и поддержку-аннотацию на _1_? (Возможно, вам нужно обновить некоторые другие зависимости) - person johann; 13.01.2018
comment
Я обновил sdk и зависимости до 26 (см. Мой файл gradle, обновленный в сообщении), но та же ошибка все еще здесь .... - person Maychell Fernandes; 13.01.2018
comment
android.support.test.espresso.AppNotIdleException: цикл для 2969 итераций более 60 секунд. Не удалось выполнить следующие условия простоя. в dalvik.system.VMStack.getThreadStackTrace (собственный метод) в java.lang.Thread.getStackTrace (Thread.java:1536) в android.support.test.espresso.base.DefaultFailureHandler.getUserFriendlyError (DefaultFailureHandler.java: .support.test.espresso.base.DefaultFailureHandler.handle (DefaultFailureHandler.java:52) по адресу android.support.test.espresso.ViewInteraction.waitForAndHandleInteractionResults (ViewInteraction.java:312) по адресу android.support.ugaredPerform.espresso. (ViewInteraction.java:167) на android.support.test.espresso.ViewInteraction.perform (ViewInteraction.java:110) на info.xxx.activities.AdviceDisplay2.adviceDisplay2 (AdviceDisplay2.java:56) на java.lang.reflect. Method.invoke (собственный метод) по адресу org.junit.runners.model.FrameworkMethod $ 1.runReflectiveCall (FrameworkMethod.java:50) по адресу org.junit.internal.runners.model.ReflectiveCallable.run (ReflectiveCallable.java:12) по адресу org.junit.internal.runners.model.ReflectiveCallable.run (ReflectiveCallable.java:12) .junit.runners.model.FrameworkMethod.invokeExpl внезапно (FrameworkMethod.java:47) на org.junit.internal.runners.statements.InvokeMethod.evaluate (InvokeMethod.java:17) на android.support.test.rule.ActivityTestRule $ ActivityStatement.evaluate (ActivityTestRule:33) .java по адресу org.junit.rules.RunRules.evaluate (RunRules.java:20) по адресу org.junit.runners.ParentRunner.runLeaf (ParentRunner.java:325) по адресу org.junit.runners.BlockJUnit4ClassRunner.RunnerChild4 ( ) в org.junit.runners.BlockJUnit4ClassRunner.runChild (BlockJUnit4ClassRunner.java:57) в org.junit.runners.ParentRunner $ 3.run (ParentRunner.java:290) в org.junit.runner. java: 71) по адресу org.junit.runners.ParentRunner.runChildren (ParentRunner.java:288) по адресу org.junit.runners.ParentRunner.access $ 000 (ParentRunner.java:58) по адресу org.junit.runners.ParentRunner $ 2. (ParentRunner.java:268) на org.junit.runners.ParentRunner.run (ParentRunner.java:363) на org.junit.runners.Suite.runChild (Suite.java:128) на org.juni t.runners.Suite.runChild (Suite.java:27) в org.junit.runners.ParentRunner $ 3.run (ParentRunner.java:290) в org.junit.runners.ParentRunner $ 1.schedule (ParentRunner.java:71) на org.junit.runners.ParentRunner.runChildren (ParentRunner.java:288) на org.junit.runners.ParentRunner.access $ 000 (ParentRunner.java:58) на org.junit.runners. ParentRunner $ 2.evaluate (ParentRunner.java:268) на org.junit.runners.ParentRunner.run (ParentRunner.java:363) на org.junit.runner.JUnitCore.run (JUnitCore.java:137) на org.java:137). runner.JUnitCore.run (JUnitCore.java:115) в android.support.test.internal.runner.TestExecutor.execute (TestExecutor.java:58) в android.support.test.runner.AndroidJUnitRunner.onStart (AndroidJUnit 375) в android.app.Instrumentation $ InstrumentationThread.run (Instrumentation.java:2074) - person johann; 15.01.2018