Crea test strumentati

I test strumentati vengono eseguiti su dispositivi Android, fisici o emulati. In questo modo, possono sfruttare le API del framework Android. I test strumentati offrono quindi una maggiore fedeltà rispetto ai test locali, anche se vengono eseguiti molto più lentamente.

Ti consigliamo di utilizzare i test di instrumentazione solo nei casi in cui devi eseguire test in base al comportamento di un dispositivo reale. AndroidX Test fornisce diverse librerie che semplificano la scrittura di test di instrumentazione, se necessario.

Configura l'ambiente di test

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

Prima di iniziare, devi aggiungere le API AndroidX Test, che ti consentono di creare ed eseguire rapidamente il codice di test di instrumentazione per le tue app. AndroidX Test include un esecutore di test JUnit 4, AndroidJUnitRunner, e API per i test funzionali della UI, come Espresso, UI Automator e Compose test.

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

Nel file build.gradle di primo livello della tua 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 nelle note di rilascio di Compose UI.

Per utilizzare le classi di test JUnit 4 e avere accesso a funzionalità come il filtro dei test, assicurati di specificare AndroidJUnitRunner come runner di strumentazione di test predefinito nel tuo progetto includendo la seguente impostazione nel file build.gradle a livello di modulo della tua app:

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

Crea una classe di test di instrumentazione

La classe di test di instrumentazione deve essere una classe di test JUnit 4 simile alla classe descritta nella sezione su come creare test locali.

Per creare una classe di test JUnit 4 con strumentazione, specifica AndroidJUnit4 come test runner predefinito.

L'esempio seguente mostra come scrivere un test di instrumentazione per verificare che l'interfaccia Parcelable sia implementata correttamente per la classe 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 di instrumentazione

I test strumentati possono essere eseguiti su dispositivi reali o emulatori. Nella guida di Android Studio puoi scoprire come:

Risorse aggiuntive

I test della UI sono in genere test strumentati che verificano il comportamento corretto della UI. Utilizzano framework come Espresso o Compose Test. Per scoprire di più, leggi la guida ai test della UI.

Per saperne di più sull'utilizzo dei test di instrumentazione, consulta le seguenti risorse.

Esempio