Search code examples
androidandroid-jetpack-composerobolectricdagger-hilt

Usage of hiltViewModel() and createComposeRule() in robolectric's test is throwing NoSuchMethodException


I run following test:

@RunWith(RobolectricTestRunner::class)
@HiltAndroidTest
class ExampleTest {
    @get:Rule
    val hiltRule = HiltAndroidRule(this)

    @get:Rule
    val composeTestRule = createComposeRule()

    @Test
    fun test() {
        composeTestRule.setContent {
            hiltViewModel<ExampleViewModel>()
        }
    }
}

@HiltViewModel
class ExampleViewModel @Inject constructor(context: Context) : ViewModel()

Inside composeTestRule.setContent i call hiltViewModel<ExampleViewModel>() which is part of androidx.hilt:hilt-navigation-compose:1.0.0-alpha03 artifact.

Unfortunately this test is throwing NoSuchMethodException while initialising viewModel.

Caused by: java.lang.NoSuchMethodException: com.example.ExampleViewModel.<init>()
    at java.base/java.lang.Class.getConstructor0(Class.java:3349)
    at java.base/java.lang.Class.newInstance(Class.java:556)
    ... 115 more

Solution

  • To fix that problem we have to use:

    @get:Rule
    val composeTestRule = createAndroidComposeRule<HiltActivity>()
    

    instead of

    @get:Rule
    val composeTestRule = createComposeRule()
    

    where HiltActivity is activity with @AndroidEntryPoint annotation from dagger hilt.

    @AndroidEntryPoint
    class HiltActivity : AppCompatActivity()