Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Hilt: allow custom injection support for tests. #4173

Open
wants to merge 1 commit into
base: master
Choose a base branch
from

Commits on Dec 1, 2023

  1. Hilt: allow custom injection support for tests.

    One of the key decisions with Hilt is bytecode rewriting. It helps simplify the developer experience, but makes things more complicated for testing. As a result Hilt provides additional testing framework that helps mitigate these concerns and allows for great flexibility when it comes to mocking and replacing dependencies for testing.
    
    Still, hilt has non-trivial compilation costs. And as the codebase growth, we've observed that the cost for test complication growth even more so than for production code. As a result there is an exploration to avoid using hilt for simpler cases where the value of DI graph in tests is very small, but the additional costs to compile are great.
    
    This diff introduces a few small touches to Hilt codegen to allow for a runtime test DI (like a simpler version of Guice) to overtake the injection.
    
    Specifically, this diff introduces `TestInjectInterceptor` class with a single empty static method `injectForTesting()`. The codegen for Activities, Fragments, Views, Services, and Broadcasts  is adjusted to have the next code:
    
    ```
    protected void inject() {
        if (!injected) {
          injected = true;
          if (TestInjectInterceptor.injectForTesting(this)) {
            return;
          }
          // rest of Hilt injection code.
      }
    ```
    
    For production or tests running under Hilt the additional code does nothing. And for production this code should be eliminated by R8. But for cases where testing framework is able to intercept a call to `TestInjectInterceptor.injectForTesting()` (like Robolectric shadow), the injection can be overtake in a consistent manner for all types of supported android entry points.
    inazaruk committed Dec 1, 2023
    Configuration menu
    Copy the full SHA
    dd64ca2 View commit details
    Browse the repository at this point in the history