返回

用 Github Actions 设置 Android 项目的 Instrumentation Tests ##

Android

在 GitHub 上利用 Instrumentation Tests 自动化 Android 项目

概述

随着移动应用开发的复杂性与日俱增,自动化测试对于确保代码质量和稳定性至关重要。Android Instrumentation Tests 是一种强大的测试方法,可以全面评估 Android 应用程序的 UI、功能和性能。本教程将深入探讨如何在 GitHub Actions 中配置 Instrumentation Tests,实现项目的持续集成和持续交付 (CI/CD)。

准备工作

  • 开源的 Android 项目(托管在 GitHub)
  • GitHub Actions 账户
  • Android Studio

步骤一:项目设置

  1. 创建 GitHub Actions 文件夹 :在项目中创建名为 .github/workflows/ 的文件夹。
  2. 添加 CI/CD 工作流文件 :在该文件夹中创建一个名为 ci.yml 的文件。
  3. 配置 GitHub Actions 工作流 :在 ci.yml 文件中添加以下内容:
name: CI/CD

on:
  push:
    branches: [ master ]

jobs:
  build:
    runs-on: ubuntu-latest

    steps:
      - uses: actions/checkout@v3
      - uses: actions/setup-java@v3
        with:
          java-version: '17'
      - run: mvn install
      - run: mvn test

步骤二:创建测试脚本

  1. 创建测试目录 :在项目中创建名为 src/androidTest/java/com/example/yourproject/ 的文件夹。
  2. 添加测试类 :在该文件夹中创建一个名为 ExampleInstrumentedTest.java 的文件。
  3. 编写测试用例 :在 ExampleInstrumentedTest.java 文件中添加以下内容:
package com.example.yourproject;

import android.app.Activity;
import android.support.test.InstrumentationRegistry;
import android.support.test.rule.ActivityTestRule;
import android.support.test.runner.AndroidJUnit4;

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

import static org.junit.Assert.*;

@RunWith(AndroidJUnit4.class)
public class ExampleInstrumentedTest {

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

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

        assertEquals("com.example.yourproject", appContext.getPackageName());
    }
}

步骤三:运行测试

  1. 推送代码到 GitHub :将您修改后的代码推送到 GitHub。
  2. 导航到 GitHub Actions :在 GitHub 上,导航到您的项目,然后点击 "Actions" 选项卡。
  3. 运行 CI/CD 工作流 :点击 "CI/CD" 工作流,然后点击 "Run workflow" 按钮。
  4. 查看测试结果 :工作流运行完成后,点击 "View run" 按钮。在 "Job" 部分,点击 "build" 作业,然后在 "Steps" 部分找到 "Run tests" 步骤。点击 "View logs" 按钮查看测试结果。

结论

通过在 GitHub Actions 中配置 Instrumentation Tests,您可以自动执行项目测试过程,提高代码质量和稳定性。自动化测试有助于尽早发现问题,防止不稳定的代码进入生产环境,从而最大限度地减少错误和提高用户体验。

常见问题解答

  1. 什么是 Instrumentation Tests?
    Instrumentation Tests 是 Android 开发中的一种自动化测试方法,可以全面测试应用程序的各个方面,包括 UI、功能和性能。
  2. 为什么在 GitHub Actions 中配置 Instrumentation Tests 很重要?
    在 GitHub Actions 中配置 Instrumentation Tests 可以实现持续集成和持续交付,从而自动化测试过程并提高代码质量。
  3. Instrumentation Tests 的工作原理是什么?
    Instrumentation Tests 使用 Android Instrumentation Framework,它允许您与正在运行的应用程序进行交互并评估其行为。
  4. 除了 GitHub Actions,还有什么其他方法可以在 Android 中自动化测试?
    除了 GitHub Actions,您还可以使用其他工具和框架来自动化 Android 测试,例如 Espresso 和 Robolectric。
  5. Instrumentation Tests 和单元测试有什么区别?
    Instrumentation Tests 测试完整的应用程序,而单元测试仅测试单个方法或类。Instrumentation Tests 覆盖范围更广,但速度也更慢。