为什么单元测试不需要 Hilt,但 UI 测试却需要 Hilt?

Why Hilt isn't necessary for unit tests, but it is necessary for UI tests?

Hilt testing guide documentaton 有一段关于单元测试的内容

Hilt isn't necessary for unit tests, since when testing a class that uses constructor injection, you don't need to use Hilt to instantiate that class. Instead, you can directly call a class constructor by passing in fake or mock dependencies, just as you would if the constructor weren't annotated:

@ActivityScoped
class AnalyticsAdapter @Inject constructor(
  private val service: AnalyticsService
) { ... }

class AnalyticsAdapterTest {

  @Test
  fun `Happy path`() {
    // You don't need Hilt to create an instance of AnalyticsAdapter.
    // You can pass a fake or mock AnalyticsService.
    val adapter = AnalyticsAdapter(fakeAnalyticsService)
    assertEquals(...)
  }
}

但是 here 您可以看到文档正在解释如何在 UI 测试中使用 Hilt。

我的问题是为什么单元测试不需要 Hilt,但 UI 测试却需要它?

通过单元测试,您可以验证 class 内部的行为,而在 UI 测试中,您可以验证 UI 给定数据的状态。在单元测试中,您不需要 Hilt 来生成对象树,您正在测试应用的一个小构建单元,一个 class,一个函数。您的单元测试所需的对象范围有限,因此这是您不需要 Hilt 来为每个单元测试构建整个对象树的另一个原因。

在单元测试中,您验证事件是否已发生、函数是否已被调用或结果是否已在给定输入的情况下返回。

Hilt 正在您的 UI 测试中注入虚假组件,您通过该测试提供呈现的数据。