在本地测试模块的安装

Play 核心库可让您在本地测试应用是否能够执行以下操作,而无需连接到 Play 商店:

本页介绍了如何将应用的拆分 APK 部署到测试设备,以便 Play 核心自动使用这些 APK 模拟从 Play 商店请求、下载和安装模块。

虽然您不需要对应用的逻辑进行任何更改,但需要满足以下要求:

构建一组 APK

您应构建应用的拆分 APK(如果您尚未执行此操作),具体操作步骤如下:

  1. 使用以下某种方法为您的应用构建 app bundle:
  2. 使用 bundletool 针对所有设备配置生成一组 APK,具体命令如下:

    bundletool build-apks --local-testing
      --bundle my_app.aab
      --output my_app.apks
    

--local-testing 标记包含 APK 清单中的元数据,告知 Play Core 库使用本地拆分 APK 测试功能模块的安装,而无需连接到 Play 商店。

将应用部署到设备

使用 --local-testing 标记构建一组 APK 后,应使用 bundletool 安装应用的基础版本,并将其他 APK 转移到设备的本地存储空间。您可以使用以下命令执行这两项操作:

bundletool install-apks --apks my_app.apks

现在,当您启动应用并完成下载和安装功能模块的用户流时,Play 核心库会使用 bundletool 转移到设备本地存储空间的 APK。

模拟网络连接错误

为了模拟从 Play 商店安装模块的过程,Play 核心库使用 SplitInstallManager 的替代方法(名为 FakeSplitInstallManager)来请求模块。当您将 bundletool--local-testing 标记一起使用来构建一组 APK 并将其部署到测试设备时,它包含元数据,指示 Play 核心库自动切换应用的 API 调用以调用 FakeSplitInstallManager,而不是 SplitInstallManager

FakeSplitInstallManager 包含一个布尔标记,当应用下次请求安装模块时,您可以启用该标记来模拟网络连接错误。如需在测试中访问 FakeSplitInstallManager,您可以使用 FakeSplitInstallManagerFactory 获取它的实例,如下所示:

Kotlin

// Creates an instance of FakeSplitInstallManager with the app's context.
val fakeSplitInstallManager = FakeSplitInstallManagerFactory.create(context)
// Tells Play Core Library to force the next module request to
// result in a network error.
fakeSplitInstallManager.setShouldNetworkError(true)

Java

// Creates an instance of FakeSplitInstallManager with the app's context.
FakeSplitInstallManager fakeSplitInstallManager =
    FakeSplitInstallManagerFactory.create(context);
// Tells Play Core Library to force the next module request to
// result in a network error.
fakeSplitInstallManager.setShouldNetworkError(true);