LaunchFragmentInContainer не может разрешить активность в Android

При написании простого теста, использующего launchFragmentInContainer, я получаю следующее сообщение об ошибке:

java.lang.RuntimeException: Unable to resolve activity for: Intent { act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER] cmp=com.myapp.appname.debug/androidx.fragment.app.testing.FragmentScenario$EmptyFragmentActivity (has extras) }

Базовый тестовый класс:

class OneFragmentTest {

    @Test
    fun testOneFragmentState_checkTitleText() {
        val args = Bundle().apply {
            putString("dummyKey", "dummyValue")
        }
        launchFragmentInContainer<OneFragment>(args)

        onView(withId(R.id.tv_title)).check(matches(withText("title here")))
    }
}

Я попытался обновить AndroidManifest.xml следующим образом:

<instrumentation
        android:name = "android.test.InstrumentationTestRunner"
        android:targetPackage = "com.myapp.appname" />

но кажется, что тег instrumentation действителен, но значения написаны красным, поэтому я предполагаю, что что-то не так с targetPackage и name.

Как избавиться от этой ошибки и запустить простой тест OneFragment с помощью launchFragmentInContainer?

Зачем вам понадобился тег <instrumentation> в AndroidManifest? Google никогда не говорил использовать его.

IgorGanapolsky 21.10.2020 17:40
38
1
12 043
5
Перейти к ответу Данный вопрос помечен как решенный

Ответы 5

Ответ принят как подходящий

Ошибка была связана с тем, как я импортировал зависимости от Gradle.

До:

androidTestImplementation("androidx.fragment:fragment-testing:1.1.0-beta01")
implementation("androidx.fragment:fragment-ktx:1.1.0-beta01")
androidTestImplementation("androidx.test:core:1.2.0")
androidTestImplementation("androidx.test:rules:1.2.0")
androidTestImplementation("androidx.test:runner:1.2.0")

После:

debugImplementation("androidx.fragment:fragment-testing:1.1.0-beta01")
debugImplementation("androidx.fragment:fragment-ktx:1.1.0-beta01")
debugImplementation("androidx.test:core:1.2.0")
debugImplementation("androidx.test:rules:1.2.0")
debugImplementation("androidx.test:runner:1.2.0")

Изменено с androidTestImplementation на debugImplementation, и это решило проблему. Компиляция и запуск, в результате зеленый тест.

Хорошо, что вы нашли решение, но developer.android.com/training/testing/set-up-project почему оно у них работает?

Astha Garg 13.06.2019 09:03

вы можете использовать debugImplementation, чтобы он не встраивался в ваши выпускные сборки

bsautner 05.08.2019 18:57

установить debugImplementation для fragment-testing должно быть достаточно, остальные тестовые зависимости могут оставаться как `androidTestImplementation

Karol Kulbaka 19.03.2020 18:40

зачем нам менять debugImplementation ?

amlwin 11.08.2020 07:31

Настройка DebugImplementation только для тестирования фрагментов допустима (как указано в Документы для Android)

Vít Kapitola 15.09.2020 15:44

Это не имеет смысла. Все тесты эспрессо включены androidTestImplementation

IgorGanapolsky 21.10.2020 17:41

Попробуйте так настроить

debugImplementation('androidx.fragment:fragment-testing:1.1.0') {
        // exclude androidx.test:core while fragment_testing depends on 1.1.0
        exclude group: 'androidx.test', module: 'core'
    }

После изменения androidTestImplementation на debugImplementation я получил ошибки в своем манифесте, что у меня нет «экспортированного» поля, и оно необходимо в Android 12 и выше, которое у меня было в моем манифесте, и он продолжал жаловаться, но этот ответ решил проблему.

Bita Mirshafiee 23.11.2021 13:39

меня устраивает

def fragmentx_version = "1.1.0"
implementation "androidx.fragment:fragment:$fragmentx_version"
debugImplementation ("androidx.fragment:fragment-testing:$fragmentx_version"){
     exclude group: 'androidx.test', module: 'core'
}
debugImplementation 'androidx.test:core-ktx:1.2.0'

@Test
fun verifyMap() {
     FragmentScenario.launchInContainer(HomeFragment::class.java)

     onView(withId(R.id.map)).check(matches(isDisplayed()))
}

Почему бы и нет androidTestImplementation?

IgorGanapolsky 21.10.2020 17:41

Я сослался на тестовые образцы для эспрессо и использовал следующий набор зависимостей в файле build.gradle на уровне приложения.

dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
implementation 'androidx.appcompat:appcompat:' + rootProject.androidxCompatVersion
implementation 'androidx.core:core-ktx:' + rootProject.androidxCoreVersion
implementation 'androidx.fragment:fragment-ktx:' + rootProject.androidxFragmentVersion

// Ideally this would only be present in test scope (Adding this fixed the issue for me)
debugImplementation 'androidx.fragment:fragment-testing:' + rootProject.androidxFragmentVersion
debugImplementation 'androidx.test:core:' + rootProject.coreVersion

testImplementation 'junit:junit:4.12'
testImplementation 'org.robolectric:robolectric:' + rootProject.robolectricVersion
testImplementation 'androidx.test:core:' + rootProject.coreVersion
testImplementation 'androidx.test.ext:junit:' + rootProject.extJUnitVersion
testImplementation 'androidx.test.espresso:espresso-core:' + rootProject.espressoVersion
testAnnotationProcessor 'com.google.auto.service:auto-service:1.0-rc4'

androidTestImplementation 'androidx.test:core:' + rootProject.coreVersion
androidTestImplementation 'androidx.test.ext:junit:' + rootProject.extJUnitVersion
androidTestImplementation 'androidx.test:runner:' + rootProject.runnerVersion
androidTestImplementation 'androidx.test.espresso:espresso-core:' + rootProject.espressoVersion
androidTestImplementation 'androidx.fragment:fragment-testing:' + rootProject.androidxFragmentVersion
androidTestImplementation 'org.robolectric:annotations:' + rootProject.robolectricVersion     }

В вашем файле build.gradle уровня проекта

ext {
buildToolsVersion = "28.0.3"
androidxCoreVersion = "1.1.0-rc02"
androidxCompatVersion = "1.1.0-rc01"
androidxFragmentVersion = "1.1.0-rc01"
coreVersion = "1.3.0-alpha03"
extJUnitVersion = "1.1.2-alpha03"
runnerVersion = "1.3.0-alpha03"
rulesVersion = "1.3.0-alpha03"
espressoVersion = "3.3.0-alpha03"
robolectricVersion = "4.3.1"   }

Внутри тестового класса изолированного фрагмента

@RunWith(AndroidJUnit4::class)
@LooperMode(LooperMode.Mode.PAUSED)
class ExampleFragmentTest{
@Test
fun launchFragmentAndVerifyTheUI(){
   /* This is used to launch the fragment in an isolated environment ( This is essentially an empty activity that
   houses that fragment ) */
   launchFragmentInContainer<ExampleFragment>()
    // Now using Espresso to verify the fragment's UI, i.e textview and verifying that its getting displayed
    onView(withId(R.id.textView)).check(matches(withText("I am a fragment")))
}  }

Я получил ту же ошибку с HiltTestActivity.kt, потому что я вставляю AndroidManifest.xml параллельно с файлом активности.

Мое исправление: переместите AndroidManifest.xml в папку java.

Другие вопросы по теме