Я пытаюсь добавить базовый тест эспрессо в свое приложение для 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());
одной и той же версии.