Android Hilt has been released and I must say I'm quite impressed. I absolutely hate Dagger which I think comprises of far too much boiler plate code, its badly documented and incredibly confusing. Hilt is of course built on top of dagger and I think this is a huge win for the Android community. Hilt decreases confusion, increases code generation and is nice and simple.
I don't want to go into what Dependency Injection (DI) is, that's been done to death.
There are two resources I found really useful to get started with Hilt:
The Hilt documentation - https://dagger.dev/hilt/
Coding with Mitch videos: https://www.youtube.com/watch?v=zTpM2olXCok
There are two things I want to talk about in this blog post:
- A really quick intro and setup of a Hilt module.
- A unit test using Robolectic.
Step 1 - The application
@HiltAndroidApp
class MyApplication : Application()
Step 2 - The Class
class Petrol(val input: String) {
    fun getTheInfo(): String {
        return input
    }
}
Step 3 - The Module
@InstallIn(ApplicationComponent::class)
@Module
class PetrolFactory {
    @Provides
    fun getPetrol(): Petrol {
        return Petrol("Petroll")
    }
}
Step 4 - The Activity
@AndroidEntryPoint
class MainActivity : AppCompatActivity() {
    @Inject
    lateinit var petrol: Petrol
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        setSupportActionBar(findViewById(R.id.toolbar))
        
        findViewById<TextView>(R.id.main_text).text = petrol.getTheInfo()
    }
}
Step 5 - The Tests
@UninstallModules(PetrolFactory::class)
@HiltAndroidTest
class MainActivityTest : RobolectricTestConfig() {
    @get:Rule
    var hiltRule = HiltAndroidRule(this)
    @Module
    @InstallIn(ApplicationComponent::class)
    class TestEngine {
        @Provides
        fun getPetrol(): Petrol {
            return Petrol("TestPetrol")
        }
    }
    @Before
    fun init() {
        hiltRule.inject()
    }
    @Test
    fun testActivityMainText() {
        val scenario = ActivityScenario.launch(MainActivity::class.java)
        scenario.onActivity {
            assertEquals("TestPetrol", it.findViewById<TextView>(R.id.main_text).text)
        }
    }
}
