# dagger


09/15/2022, 4:48 AM
I have setup dagger in my project, but struggling with Unit testing any one have any good articles or GitHub repo that can help


09/21/2022, 3:42 AM
Take a look at the dagger testing page: I’m not a big fan of component inheritance as they suggest (as it doesn’t work with anvil, which is a whole separate discussion). I prefer use interfaces for things like injection, accessors, subcomponent creators, etc… And then i develop my app in such a way that outside of the construction of your component (likely in Application.onCreate), nothing else in your app knows what actual component type is there. Just that it’s something that implements certain interfaces.
Copy code
interface MyInjectors {
   fun inject(activity: MyActivity)

fun MyComponent: MyInjectors {
I then use this custom class to hold components and retrieve whatever registered component implements the requested interface. when i created the component, i register it with this registry.
Copy code
object ComponentRegistry {
    internal val _components = mutableSetOf<Any>()

    fun add(component: Any) {

    fun remove(component: Any): Boolean =

    val size: Int
        get() = _components.size

    fun clear() = _components.clear()

    inline fun <reified T> hasComponent() =

    inline fun <reified T> getOrNull(): T? =

    inline fun <reified T> get(): T =

    inline fun <reified T> replace(component: Any) {
        getOrNull<T>()?.let { remove(it) }
And at your injection point:
Copy code
If you follow this pattern, it becomes very easy to replace your regular app component with a completely different component when doing both unit tests and espresso tests.