Что бы запустить ExampleUnitTest, но не найти ExampleInstrumentedTest? - PullRequest
1 голос
/ 13 марта 2020

Android Studio: 3.6.1 Gradle: gradle-5.6.4-all

Я готов протестировать свое приложение и обнаружил, что Android Studio создает примеры модульных и инструментальных тестов. Итак, я щелкаю правой кнопкой мыши ExampleUnitTest , выбираю «Выполнить» и все работает нормально. Однако, когда я делаю это для ExampleInstrumentedTest , происходит сбой со следующим сообщением об ошибке:

Процесс завершен с кодом выхода 1 Класс не найден: "com.example.jbiss.petminder .ExampleInstrumentedTest "

Однако ExampleInstrumentedTest находится по умолчанию androidTest путь ( ... \ app \ src \ androidTest \ java \ com \ example \ jbiss \ petminder ) и ExampleUnitTest находится по умолчанию test path ( ... \ app \ src \ test \ java \ com \ пример \ jbiss \ petminder ).

Хотя я изменил автоматически сгенерированный исходный код Android Studio, чтобы начать экспериментировать с тестовым кодированием, это не должно иметь ничего общего с не найденным классом : "com.example.jbiss.petminder.ExampleInstrumentedTest" ошибка. Вот мой измененный код (с использованием автоматически сгенерированного ExampleInstrumentedTest кода в качестве базовой линии):

package com.example.jbiss.petminder;

import android.content.Context;

import com.example.jbiss.petminder.activities.MainActivity;

import androidx.test.espresso.accessibility.AccessibilityChecks;
import androidx.test.filters.SmallTest;
import androidx.test.platform.app.InstrumentationRegistry;
import androidx.test.ext.junit.runners.AndroidJUnit4;
import androidx.test.rule.ActivityTestRule;

import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.runner.RunWith;

import static androidx.test.espresso.Espresso.onView;
import static androidx.test.espresso.action.ViewActions.click;
import static androidx.test.espresso.assertion.ViewAssertions.matches;
import static androidx.test.espresso.matcher.ViewMatchers.withContentDescription;
import static androidx.test.espresso.matcher.ViewMatchers.withId;
import static org.junit.Assert.*;

/**
* Instrumentation test, which will execute on an Android device.
*
* @see <a href="http://d.android.com/tools/testing">Testing documentation</a>
*/
@RunWith(AndroidJUnit4.class)
@SmallTest
public class ExampleInstrumentedTest {

@Before
public void setUp(){
AccessibilityChecks.enable();
}

@Rule
public ActivityTestRule<MainActivity> mMainActivityActivityTestRule =
new ActivityTestRule<>(MainActivity.class);

@Test
public void useAppContext() throws Exception {
// Context of the app under test.
Context appContext = InstrumentationRegistry.getInstrumentation().getTargetContext();

assertEquals("com.example.jbiss.petminder", appContext.getPackageName());
onView(withId(R.id.action_add_pet)).perform(click()).check(matches(withContentDescription(R.layout.activity_add_pet)));
}
}

Вот файл build.gradle моего приложения:

apply plugin: 'com.android.application'

android {
compileSdkVersion 28
packagingOptions {
exclude 'META-INF/DEPENDENCIES'
}
buildToolsVersion '28.0.3'
defaultConfig {
applicationId "com.example.jbiss.petminder"
minSdkVersion 24
targetSdkVersion 28
versionCode 1
versionName "1.0"
testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
}
buildTypes {
release {
minifyEnabled false
proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
}
}

compileOptions {
encoding "UTF-8"
sourceCompatibility JavaVersion.VERSION_1_8
targetCompatibility JavaVersion.VERSION_1_8
}

dataBinding {
enabled = true
}

// Gradle automatically adds 'android.test.runner' as a dependency.
useLibrary 'android.test.runner'

useLibrary 'android.test.base'
useLibrary 'android.test.mock'

testOptions {
unitTests.includeAndroidResources = true
}
}

dependencies {
def nav_version = "2.3.0-alpha03"

implementation "android.arch.navigation:navigation-fragment-ktx:1.0.0"
implementation "android.arch.navigation:navigation-ui-ktx:1.0.0"

// Java language implementation: navigation
implementation "androidx.navigation:navigation-fragment:$nav_version"
implementation "androidx.navigation:navigation-ui:$nav_version"

// Dynamic Feature Module Support
implementation "androidx.navigation:navigation-dynamic-features-fragment:$nav_version"

// Testing Navigation
androidTestImplementation "androidx.navigation:navigation-testing:$nav_version"

// use -ktx for Kotlin
implementation "android.arch.navigation:navigation-ui:$nav_version"

// use -ktx for Kotlin

//noinspection GradleCompatible
implementation 'com.android.support:support-v4:28.1.0'
implementation
implementation fileTree(include: ['*.jar'], dir: 'libs')
implementation 'com.android.support:appcompat-v7:28.1.0'
implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
implementation 'com.android.support:design:28.1.0'
implementation 'com.android.support:cardview-v7:28.1.0'
implementation 'androidx.recyclerview:recyclerview:1.1.0'
implementation 'com.google.android.material:material:1.1.0'
implementation 'com.android.support:mediarouter-v7:28.1.0'

/**
* directly from https://developer.android.com/topic/libraries/architecture/adding-components#lifecycle
*/
def lifecycle_version = "2.2.0"
def arch_version = "2.1.0"
def room_version = "2.2.4"

// ViewModel
implementation "androidx.lifecycle:lifecycle-viewmodel:$lifecycle_version"
// LiveData
implementation "androidx.lifecycle:lifecycle-livedata:$lifecycle_version"
// Lifecycles only (without ViewModel or LiveData)
implementation "androidx.lifecycle:lifecycle-runtime:$lifecycle_version"

// Saved state module for ViewModel
implementation "androidx.lifecycle:lifecycle-viewmodel-savedstate:$lifecycle_version"

// Annotation processor
annotationProcessor "androidx.lifecycle:lifecycle-compiler:$lifecycle_version"
// alternately - if using Java8, use the following instead of lifecycle-compiler
implementation "androidx.lifecycle:lifecycle-common-java8:$lifecycle_version"

// optional - helpers for implementing LifecycleOwner in a Service
implementation "androidx.lifecycle:lifecycle-service:$lifecycle_version"

// optional - ProcessLifecycleOwner provides a lifecycle for the whole application process
implementation "androidx.lifecycle:lifecycle-process:$lifecycle_version"

// optional - ReactiveStreams support for LiveData
implementation "androidx.lifecycle:lifecycle-reactivestreams:$lifecycle_version"

// optional - Test helpers for LiveData
testImplementation "androidx.arch.core:core-testing:$arch_version"

implementation "androidx.lifecycle:lifecycle-reactivestreams:$lifecycle_version"

// optional - Test helpers for LiveData
testImplementation "androidx.arch.core:core-testing:$arch_version"
implementation "androidx.room:room-runtime:$room_version"
annotationProcessor "androidx.room:room-compiler:$room_version"

// use kapt for Kotlin

// optional - RxJava support for Room

//implementation "androidx.room:room-rxjava2:$room_version"

// optional - Guava support for Room, including Optional and ListenableFuture

//implementation "androidx.room:room-guava:$room_version"

// Test helpers
testImplementation "androidx.room:room-testing:$room_version"
testImplementation 'org.testng:testng:6.9.10'

// Required -- JUnit 4 framework
testImplementation 'junit:junit:4.12'
// Optional -- Robolectric environment
testImplementation 'androidx.test:core:1.2.0'
// Optional -- Mockito framework
testImplementation 'org.mockito:mockito-core:2.19.0'
implementation 'androidx.appcompat:appcompat:1.1.0'

implementation 'com.google.api-client:google-api-client:1.30.2'

// Core library
androidTestImplementation 'androidx.test:core:1.2.0'

// AndroidJUnitRunner and JUnit Rules
androidTestImplementation 'androidx.test:runner:1.2.0'
androidTestImplementation 'androidx.test:rules:1.2.0'

// Assertions
androidTestImplementation 'androidx.test.ext:junit:1.1.1'
androidTestImplementation 'androidx.test.ext:truth:1.2.0'
androidTestImplementation 'com.google.truth:truth:0.42'

// Espresso dependencies
androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'
androidTestImplementation 'androidx.test.espresso:espresso-contrib:3.2.0'
androidTestImplementation 'androidx.test.espresso:espresso-intents:3.2.0'
androidTestImplementation 'androidx.test.espresso:espresso-accessibility:3.2.0'
androidTestImplementation 'androidx.test.espresso:espresso-web:3.2.0'
androidTestImplementation 'androidx.test.espresso.idling:idling-concurrent:3.2.0'

// The following Espresso dependency can be either "implementation"
// or "androidTestImplementation", depending on whether you want the
// dependency to appear on your APK's compile classpath or the test APK
// classpath.
androidTestImplementation 'androidx.test.espresso:espresso-idling-resource:3.2.0'
// debugImplementation because LeakCanary should only run in debug builds.
debugImplementation 'com.squareup.leakcanary:leakcanary-android:2.2'
// Optional -- Hamcrest library
androidTestImplementation 'org.hamcrest:hamcrest-library:1.3'
// Optional -- UI testing with UI Automator
androidTestImplementation 'androidx.test.uiautomator:uiautomator:2.2.0'

}

configurations.all {
resolutionStrategy.eachDependency { DependencyResolveDetails details ->
def requested = details.requested
if (requested.group == 'com.android.support') {
//if (requested.group == "androidx") {
if (!requested.name.startsWith("multidex")) {
details.useVersion '25.3.1'
}
}
}
}

Хотя у меня могут быть другие проблемы в моем коде, что может привести к тому, что эта ошибка не найдет существующий ExampleInstrumentedTest файл с public class ExampleInstrumentedTest{}, явно указанным в этом файле?

Код, похоже, отформатирован как показано в Построить инструментированные модульные тесты

Следующее не дало ответа:

Ответы [ 2 ]

1 голос
/ 18 марта 2020

OK. из моего разговора по ахасбини я обнаружил, что у меня могут быть некоторые проблемы с учебой. Итак, я сделал следующее изменение в своем файле build.gradle:

С:

// Assertions
androidTestImplementation 'androidx.test.ext:truth:1.2.0'
androidTestImplementation 'com.google.truth:truth:0.42'

Кому:

// Assertions
androidTestImplementation 'androidx.test.ext:junit:1.1.1'
androidTestImplementation 'androidx.test.ext:truth:1.1.1'{
    exclude group: "com.google.truth", module: "truth"
}
androidTestImplementation 'com.google.truth:truth:0.44'{
   exclude group: "org.checkerframework", module: "checker-compat-qual"
   exclude group: "com.google.errorprone", module: "error_prone_annotations"
}

Теперь я получаю следующую ошибку :

  • Что пошло не так: возникла проблема при оценке проекта ': app'.

    Не удалось найти метод androidx.test.ext: true: 1.1.1 () для аргументов [build_ezdi8oaa9gsnmfo7o2e18xyfx$_run_closure2$_closure11@6b8f394a] для объекта типа org.gradle.api.internal.artifacts.dsl.dependencies.DefaultDependencyHandler.

Итак, похоже, что это проблема с документацией для разработчика. android .com, потому что я следую инструкциям на его страницах для разработки моего тестового кода и Зависимости Gradle говорит мне использовать следующее:

// Assertions
androidTestImplementation 'androidx.test.ext:junit:1.0.0'
androidTestImplementation 'androidx.test.ext:truth:1.0.0'
androidTestImplementation 'com.google.truth:truth:0.42'

Этот код приводит к ошибке «not found». Тем не менее, все еще существует проблема, поскольку никто ничего не говорит ни о том, чтобы использовать этот {exclude ...} материал, ни какую версию androidx.test.ext: true использовать для получения функционального кода в официальной документации. Обратите внимание, что я использую версии 1.1.1, потому что Gradle в Android Studio сообщил, что для androidx.test.ext: junit существует «более новая версия».

ПРИМЕЧАНИЕ. Во-первых, мой код Instrumented Test НЕ использует методы Истины, поэтому, почему это происходит, не имеет смысла. Во-вторых, я нашел Truth.dev, когда искал текущие версии, и попытался использовать то, что они сказали использовать в «Как использовать Truth: Gradle», и это не удалось с ошибкой «Not found ...».

1 голос
/ 14 марта 2020

Существует смешивание между androidx.test и android.support.test / android.test, которое не рекомендуется. Изменение testInstrumentationRunner на приведенное ниже может решить проблему:

testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"

Вот образец , который можно использовать для использования androidx.test в качестве основной платформы тестирования.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...