Skip to content

Hilt: handle Services with injection automatically started in instrumentation tests #2016

Closed
@francescocervone

Description

@francescocervone

Let's assume I have a service that is automatically started at the app startup and it is required by some third party library.
This service needs some fields to be injected in the onCreate method.

@AndroidEntryPoint
class MyMessagingService : FirebaseMessagingService() {
  @Inject internal lateinit var dep1: Dep1
  @Inject internal lateinit var dep2: Dep2
  ...
}

Then I have a @HiltAndroidTest that runs hiltRule.inject() in its @Before function.

@AndroidEntryPoint
class MyTest {
  @get:Rule val hiltRule = HiltAndroidRule(this)
  @Before fun inject() {
    hiltRule.inject()
  }
  ...
}

Unfortunately, the way Hilt injection works in tests generates a race condition between hiltRule.inject() and MyMessagingService#onCreate. If the latter gets executed before hiltRule.inject() the test will crash because dependency graph has not been created yet.

How can I avoid this issue?

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions