在 robolectric 的测试中使用 hiltViewModel() 和 createComposeRule() 会抛出 NoSuchMethodException

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

我运行以下测试:

@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()

composeTestRule.setContent 内部,我调用 hiltViewModel<ExampleViewModel>(),它是 androidx.hilt:hilt-navigation-compose:1.0.0-alpha03 工件的一部分。

不幸的是,此测试在初始化 viewModel 时抛出 NoSuchMethodException

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

要解决这个问题,我们必须使用:

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

而不是

@get:Rule
val composeTestRule = createComposeRule()

其中 HiltActivity 是 activity,带有来自匕首柄的 @AndroidEntryPoint 注释。

@AndroidEntryPoint
class HiltActivity : AppCompatActivity()