Hilt testing guide documentaton has this paragraph about Unit test
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(...)
}
}
But here you can see that documentation is explaining how to use Hilt in UI test.
My question is why Hilt isn't necessary for unit tests, but it is necessary for UI tests?
CodePudding user response:
With unit tests you verify behavior inside the classes, while in UI test you verify UI state given data. In unit test you don't need Hilt to generate a object tree, you are testing a small building unit of your app, a class, a function. Your unit test have limited scope of objects needed, so that's another reason why you don't need Hilt to build entire tree of objects each unit test.
In unit test you verify that an event have happened, a function has been called or a result has been returned given an input.
Hilt is injecting fake components in your UI test through which you are providing data that is rendered.