Crea test strumentati

I test strumentati vengono eseguiti sui dispositivi Android, fisici o emulati. Come possono sfruttare le API del framework Android. Test strumentati pertanto offrono più fedeltà rispetto ai test locali, anche se eseguono lentamente.

Ti consigliamo di utilizzare i test strumentati solo nei casi in cui devi eseguire test rispetto il comportamento di un dispositivo reale. AndroidX Test fornisce diverse librerie che semplificano la scrittura di test strumentati quando necessario.

Configura l'ambiente di test

Nel tuo progetto Android Studio, archivi i file di origine per test in module-name/src/androidTest/java/. Questa directory esiste già quando crei un nuovo progetto e contiene un test strumentato di esempio.

Prima di iniziare, devi aggiungere le API AndroidX Test, che consentono di creare ed eseguire codice di test strumentato per le tue app. Il test AndroidX include un Esecutore test JUnit 4, AndroidJUnitRunner e API per i test funzionali dell'interfaccia utente come Espresso, UI Automator e Compose test.

Devi anche configurare le dipendenze di test di Android per fare in modo che il tuo progetto utilizza l'esecutore del test e le API delle regole fornite da AndroidX Test.

Nel file build.gradle di primo livello dell'app, devi specificare queste librerie come dipendenze:

dependencies {
    androidTestImplementation "androidx.test:runner:$androidXTestVersion"
    androidTestImplementation "androidx.test:rules:$androidXTestVersion"
    // Optional -- UI testing with Espresso
    androidTestImplementation "androidx.test.espresso:espresso-core:$espressoVersion"
    // Optional -- UI testing with UI Automator
    androidTestImplementation "androidx.test.uiautomator:uiautomator:$uiAutomatorVersion"
    // Optional -- UI testing with Compose
    androidTestImplementation "androidx.compose.ui:ui-test-junit4:$compose_version"
}

Puoi trovare le versioni più recenti nelle Note di rilascio di AndroidX e in Compose Note di rilascio della UI.

Per utilizzare le classi di test dell'unità JUnit 4 e avere accesso a funzioni quali i filtri di prova, assicurati di specificare AndroidJUnitRunner come strumentazione di test predefinita runner nel tuo progetto includendo la seguente impostazione nella file build.gradle a livello di modulo:

android {
    defaultConfig {
        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }
}

Crea una lezione di test instrumentata

La classe di test con strumentazione deve essere una classe di test JUnit 4 simile alla il corso descritto nella sezione su come creare test locali.

Per creare una classe di test JUnit 4 instrumentata, specifica AndroidJUnit4 come predefinito del test.

L'esempio seguente mostra come scrivere un test instrumentato per verificare che l'interfaccia Parcelable sia implementata correttamente per Corso LogHistory:

Kotlin

import android.os.Parcel
import android.text.TextUtils.writeToParcel
import androidx.test.filters.SmallTest
import androidx.test.runner.AndroidJUnit4
import com.google.common.truth.Truth.assertThat
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith

const val TEST_STRING = "This is a string"
const val TEST_LONG = 12345678L

// @RunWith is required only if you use a mix of JUnit3 and JUnit4.
@RunWith(AndroidJUnit4::class)
@SmallTest
class LogHistoryAndroidUnitTest {
    private lateinit var logHistory: LogHistory

    @Before
    fun createLogHistory() {
        logHistory = LogHistory()
    }

    @Test
    fun logHistory_ParcelableWriteRead() {
        val parcel = Parcel.obtain()
        logHistory.apply {
            // Set up the Parcelable object to send and receive.
            addEntry(TEST_STRING, TEST_LONG)

            // Write the data.
            writeToParcel(parcel, describeContents())
        }

        // After you're done with writing, you need to reset the parcel for reading.
        parcel.setDataPosition(0)

        // Read the data.
        val createdFromParcel: LogHistory = LogHistory.CREATOR.createFromParcel(parcel)
        createdFromParcel.getData().also { createdFromParcelData: List<Pair<String, Long>> ->

            // Verify that the received data is correct.
            assertThat(createdFromParcelData.size).isEqualTo(1)
            assertThat(createdFromParcelData[0].first).isEqualTo(TEST_STRING)
            assertThat(createdFromParcelData[0].second).isEqualTo(TEST_LONG)
        }
    }
}

Java

import android.os.Parcel;
import android.util.Pair;
import androidx.test.runner.AndroidJUnit4;
import com.google.common.truth.Truth.assertThat;
import java.util.List;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;

// @RunWith is required only if you use a mix of JUnit3 and JUnit4.
@RunWith(AndroidJUnit4.class)
public class LogHistoryAndroidUnitTest {

    public static final String TEST_STRING = "This is a string";
    public static final long TEST_LONG = 12345678L;
    private LogHistory mLogHistory;

    @Before
    public void createLogHistory() {
        mLogHistory = new LogHistory();
    }

    @Test
    public void logHistory_ParcelableWriteRead() {
        // Set up the Parcelable object to send and receive.
        mLogHistory.addEntry(TEST_STRING, TEST_LONG);

        // Write the data.
        Parcel parcel = Parcel.obtain();
        mLogHistory.writeToParcel(parcel, mLogHistory.describeContents());

        // After you're done with writing, you need to reset the parcel for reading.
        parcel.setDataPosition(0);

        // Read the data.
        LogHistory createdFromParcel = LogHistory.CREATOR.createFromParcel(parcel);
        List<Pair<String, Long>> createdFromParcelData
                = createdFromParcel.getData();

        // Verify that the received data is correct.
        assertThat(createdFromParcelData.size()).isEqualTo(1);
        assertThat(createdFromParcelData.get(0).first).isEqualTo(TEST_STRING);
        assertThat(createdFromParcelData.get(0).second).isEqaulTo(TEST_LONG);
    }
}

Esegui test instrumentati

I test strumentati possono essere eseguiti su emulatori o dispositivi reali. Nell'app Nella guida di Studio puoi imparare a:

Risorse aggiuntive

I test UI sono in genere test strumentati che verificano il corretto comportamento delle l'interfaccia utente. Usano framework come Espresso o Compose Test. Per ulteriori informazioni leggi la guida al test dell'interfaccia utente.

Per ulteriori informazioni sull'uso dei test di strumentazione, consulta quanto segue Google Cloud.

Anteprima

Codelab