

本文属于机器翻译版本。若本译文内容与英语原文存在差异，则一律以英文原文为准。

# 将 Device Farm 与 Gradle 构建系统集成
<a name="aws-device-farm-android-gradle-plugin"></a>

利用 Device Farm Gradle 插件，AWS Device Farm 可与 Android Studio 中的 Gradle 构建系统集成。有关更多信息，请参阅 [Gradle](https://gradle.org)。

**注意**  
要下载 Gradle 插件，请转至[GitHub](https://github.com/awslabs/aws-device-farm-gradle-plugin)并按照中的说明进行操作。[构建 Device Farm Gradle 插件](#aws-device-farm-gradle-plugin-building)

Device Farm Gradle 插件可在您的 Android Studio 环境中提供 Device Farm 功能。您可以在由 Device Farm 托管的真实 Android 手机和平板电脑上开始测试。

本节包含设置和使用 Device Farm Gradle 插件的一系列过程。

**Topics**
+ [依赖项](#aws-device-farm-gradle-plugin-dependencies)
+ [步骤 1：构建 AWS Device Farm Gradle 插件](#aws-device-farm-gradle-plugin-building)
+ [步骤 2：设置 AWS Device Farm Gradle 插件](#aws-device-farm-gradle-plugin-setting-up)
+ [步骤 3：在 Device Farm Gradle 插件中生成 IAM 用户](#aws-device-farm-gradle-plugin-generating-iam-user)
+ [步骤 4：配置测试类型](#aws-device-farm-gradle-plugin-configuring-test-types)

## 依赖项
<a name="aws-device-farm-gradle-plugin-dependencies"></a>

**运行时**
+ Device Farm Gradle 插件需要 AWS 移动 SDK 1.10.15 或更高版本。有关更多信息以及若要安装开发工具包，请参阅 [AWS 移动开发工具包](https://aws.amazon.com/mobile/sdk/)。
+ Android tools builder test api 0.5.2
+ Apache Commons Lang3 3.3.4

**对于单元测试**
+ Testng 6.8.8
+ Jmockit 1.19
+ Android gradle tools 1.3.0

## 步骤 1：构建 AWS Device Farm Gradle 插件
<a name="aws-device-farm-gradle-plugin-building"></a>

利用此插件，AWS Device Farm 可与 Android Studio 中的 Gradle 构建系统集成。有关更多信息，请参阅 [Gradle](https://gradle.org)。

**注意**  
构建此插件是可选的。通过 Maven Central 发布了此插件。如果您希望允许 Gradle 直接下载此插件，请跳过此步骤并跳转到 [步骤 2：设置 AWS Device Farm Gradle 插件](#aws-device-farm-gradle-plugin-setting-up)。

**构建此插件**

1. 前往[GitHub](https://github.com/awslabs/aws-device-farm-gradle-plugin)并克隆存储库。

1. 使用 `gradle install` 构建此插件。

   此插件将安装到您的本地 maven 存储库。

下一步: [步骤 2：设置 AWS Device Farm Gradle 插件](#aws-device-farm-gradle-plugin-setting-up)

## 步骤 2：设置 AWS Device Farm Gradle 插件
<a name="aws-device-farm-gradle-plugin-setting-up"></a>

请使用此处的过程克隆存储库并安装插件：[构建 Device Farm Gradle 插件](#aws-device-farm-gradle-plugin-building) (如果您尚未执行此操作)。

**配置 AWS Device Farm Gradle 插件**

1. 向 `build.gradle` 中的依赖项列表添加插件项目。

   ```
       buildscript {
   
           repositories {        
               mavenLocal()            
               mavenCentral()            
           }
   
           dependencies {        
               classpath 'com.android.tools.build:gradle:1.3.0'           
               classpath 'com.amazonaws:aws-devicefarm-gradle-plugin:1.0'            
           }        
       }
   ```

1. 在 `build.gradle` 文件中配置插件。以下测试特定的配置应作为您的指南：

   ```
   apply plugin: 'devicefarm'
   
   devicefarm {
   
       // Required. The project must already exist. You can create a project in the AWS Device Farm console.
       projectName "My Project" // required: Must already exist.
   
       // Optional. Defaults to "Top Devices"
       // devicePool "My Device Pool Name"
       
       // Optional. Default is 150 minutes
       // executionTimeoutMinutes 150
       
       // Optional. Set to "off" if you want to disable device video recording during a run. Default is "on"
       // videoRecording "on"
       
       // Optional. Set to "off" if you want to disable device performance monitoring during a run. Default is "on"
       // performanceMonitoring "on"
       
       // Optional. Add this if you have a subscription and want to use your unmetered slots
       // useUnmeteredDevices()
       
       // Required. You must specify either accessKey and secretKey OR roleArn. roleArn takes precedence. 
       authentication {
           accessKey "AKIAIOSFODNN7EXAMPLE"
           secretKey "wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY"
           
           // OR
           
           roleArn "arn:aws:iam::111122223333:role/DeviceFarmRole"
       }
   
       // Optionally, you can 
       // - enable or disable Wi-Fi, Bluetooth, GPS, NFC radios
       // - set the GPS coordinates
       // - specify files and applications that must be on the device when your test runs
       devicestate {
           // Extra files to include on the device.
           // extraDataZipFile file("path/to/zip")
           
           // Other applications that must be installed in addition to yours. 
           // auxiliaryApps files(file("path/to/app"), file("path/to/app2"))
           
           // By default, Wi-Fi, Bluetooth, GPS, and NFC are turned on.
           // wifi "off"
           // bluetooth "off"
           // gps "off"
           // nfc "off"
           
           // You can specify GPS location. By default, this location is 47.6204, -122.3491
           // latitude 44.97005
           // longitude -93.28872
       }
    
       // By default, the Instrumentation test is used.
       // If you want to use a different test type, configure it here.
       // You can set only one test type (for example, Calabash, Fuzz, and so on)
    
       // Fuzz
       // fuzz { }
   
       // Calabash
       // calabash { tests file("path-to-features.zip") }
          
   }
   ```

1. 使用以下任务运行 Device Farm 测试：`gradle devicefarmUpload`。

   构建输出将输出一个指向 Device Farm 控制台的链接，您可在其中监控测试执行情况。

下一步: [在 Device Farm Gradle 插件中生成 IAM 用户](#aws-device-farm-gradle-plugin-generating-iam-user)

## 步骤 3：在 Device Farm Gradle 插件中生成 IAM 用户
<a name="aws-device-farm-gradle-plugin-generating-iam-user"></a>

AWS Identity and Access Management (IAM) 可帮助您管理使用 AWS 资源的权限和策略。本主题演示如何生成具有 AWS Device Farm 资源访问权限的 IAM 用户。

如果您还没有完成步骤 1 和 2，请先完成这两个步骤，然后再生成 IAM 用户。

我们建议您不要使用 AWS 根账户来访问 Device Farm。而应在您的 AWS 账户中创建一个新 IAM 用户（或使用现有的 IAM 用户），然后使用该 IAM 用户访问 Device Farm。

**注意**  
用于完成以下步骤的 AWS 根账户或 IAM 用户必须有权创建以下 IAM 策略并将其附加到 IAM 用户。有关更多信息，请参阅[使用策略](https://docs.aws.amazon.com/IAM/latest/UserGuide/policies_manage.html)。

**使用适当访问策略在 IAM 中创建新用户**

1. 使用 [https://console.aws.amazon.com/iam/](https://console.aws.amazon.com/iam/) 打开 IAM 控制台。

1. 选择**用户**。

1. 选择**创建新用户**。

1. 请输入您选择的用户名称。

   例如 **GradleUser**。

1. 选择**创建**。

1. 选择**下载凭证**，并将这些凭证保存在您之后可以轻松检索它们的位置。

1. 选择**关闭**。

1. 在列表中选择用户名称。

1. 在**权限**下，通过单击右侧的向下箭头来展开**内联策略**标题。

1. 选择**单击此处**，其中显示**没有任何内联策略可显示。要创建一个，请单击此处**。

1. 在**设置权限**屏幕上，选择**自定义策略**。

1. 选定**选择**。

1. 为您的策略提供名称，例如 **AWSDeviceFarmGradlePolicy**。

1. 将以下策略粘贴到**策略文档**中。

------
#### [ JSON ]

****  

   ```
       {
           "Version":"2012-10-17",		 	 	 
           "Statement": [
               {
                   "Sid": "DeviceFarmAll",
                   "Effect": "Allow",
                   "Action": [ "devicefarm:*" ],
                   "Resource": [ "*" ]
               }
           ]
       }
   ```

------

1. 选择**应用策略**。

下一步：[配置测试类型](#aws-device-farm-gradle-plugin-configuring-test-types)。

有关更多信息，请参阅[创建 IAM 用户 (AWS 管理控制台)](https://docs.aws.amazon.com/IAM/latest/UserGuide/Using_SettingUpUser.html#Using_CreateUser_console) 或 [设置](setting-up.md)。

## 步骤 4：配置测试类型
<a name="aws-device-farm-gradle-plugin-configuring-test-types"></a>

默认情况下，AWS Device Farm Gradle 插件运行 [适用于 Android 的 Instrumentation 与 AWS Device Farm](test-types-android-instrumentation.md) 测试。如果要运行自己的测试或指定其他参数，可以选择配置测试类型。本主题提供有关每个可用测试类型的信息，以及您需要在 Android Studio 中执行哪些操作才能将其配置为可供使用。有关 Device Farm 中可用测试类型的更多信息，请参阅 [AWS Device Farm 中的测试框架和内置测试](test-types.md)。

如果您还没有完成步骤 1 到 3，请先完成这些步骤，然后再配置测试类型。

**注意**  
如果您要使用[设备槽](how-to-purchase-device-slots.md)，请将其启用，设备槽功能默认情况下处于禁用状态。

### Appium
<a name="configuring-test-types-appium"></a>

Device Farm 支持 Appium Java 和 Android JUnit 版 TestNG。
+ [Appium（在 Java () JUnit 下）](https://docs.aws.amazon.com//devicefarm/latest/developerguide/test-types-appium.html)
+ [Appium [在 Java（TestNG）下]](https://docs.aws.amazon.com//devicefarm/latest/developerguide/test-types-appium.html)

您可以选择 `useTestNG()` 或 `useJUnit()`。`JUnit` 是默认值，不需要显式指定。

```
    appium {
        tests file("path to zip file") // required
        useTestNG() // or useJUnit()
    }
```

### 内置：模糊
<a name="configuring-test-types-built-in-fuzz"></a>

Device Farm 提供内置模糊测试类型，该测试类型将用户界面事件随机发送至设备，然后报告结果。

```
    fuzz {

       eventThrottle 50 // optional default
       eventCount 6000  // optional default
       randomizerSeed 1234 // optional default blank

     }
```

有关更多信息，请参阅 [运行 Device Farm 的内置模糊测试（Android 和 iOS）](test-types-built-in-fuzz.md)。

### Instrumentation
<a name="configuring-test-types-instrumentation"></a>

Device Farm 支持安卓版仪器（JUnit、Espresso、Robotium 或任何基于仪器的测试）。有关更多信息，请参阅 [适用于 Android 的 Instrumentation 与 AWS Device Farm](test-types-android-instrumentation.md)。

在 Gradle 中运行 Instrumentation 时， 使用从 **androidTest** 目录生成的 `.apk` 文件作为测试源。

```
    instrumentation { 

        filter "test filter per developer docs" // optional

    }
```