MutableDagger is a code generation tool designed to simplify the manipulation of Dagger dependency graphs in unit tests. It allows developers to declaratively mutate existing Dagger components by adding or removing modules and overriding specific bindings directly within the test class, similar to features often found in Hilt testing but without requiring a full migration to Hilt.
See go/mutabledagger for the detailed design.
For unit tests that that rely on Dagger-injected dependencies, the tool provides these features
MutableDagger uses annotations processed by a KSP processor to generate the necessary Dagger component for your test.
@MutatedComponent: Apply this to your test class.
target: Specifies the production Dagger component interface you want to modify.installModules: (Optional) An array of module classes to add to the generated component. Useful for test-specific providers.uninstallModules: (Optional) An array of module classes to remove from the transitive graph of the target component.unbindValues: (Optional) An array of types for which any existing bindings in the original modules should be removed.@BindValue: Apply this to fields or properties within your test class (the one annotated with @MutatedComponent).
@BindsInstance binding in the generated component's Builder.Let's say you have a production component MyAppComponent:
interface MyAppComponent { fun inject(myClass: MyClass) @Component.Builder interface Builder { @BindsInstance fun application(app: Application): Builder fun build(): MyAppComponent } }
Without MutableDagger, testing MyClass with a mock DependencyA might require creating a whole new component. You would also need to manually define and maintain AllModulesExceptA.
// Manual test component @Component(modules = [AllModulesExceptA::class, TestModule::class]) interface TestAppComponent : MyAppComponent { @Component.Builder interface Builder : MyAppComponent.Builder { @BindsInstance fun bindDependencyA(depA: DependencyA): Builder override fun build(): TestAppComponent } } // In your test class MyClassTest { val mockDepA: DependencyA = mock() fun setup() { val testComponent = DaggerTestAppComponent.builder() .application(myApp) .bindDependencyA(mockDepA) .build() // ... inject ... } }
With MutableDagger, you can modify MyAppComponent directly in your test class:
import com.android.tools.dagger.mutation.annotations.MutatedComponent import com.android.tools.dagger.mutation.annotations.BindValue @MutatedComponent( target = MyAppComponent::class, installModules = [TestModule::class], // Optional test-specific modules ) class MyClassTest { @BindValue val mockDepA: DependencyA = mock() @BindValue @MyQualifier val qualifiedDepB: DependencyB = mock() fun setup() { // 'mutatedComponentBuilder()' is generated by the processor val testComponentBuilder = mutatedComponentBuilder() // Add any instances required by the base builder val testComponent = testComponentBuilder .application(myApp) .build() // ... inject ... } }