android 如何在编写UI测试中注入视图模型?

ymdaylpp  于 2023-05-15  发布在  Android
关注(0)|答案(1)|浏览(142)

我的可组合函数

@Composable
fun MyScreen(
    myViewModel: MyViewModel,
    navController: NavController
){}

我的viewodel类

@HiltViewModel
class MyViewModel @Inject constructor(
    val myUseCases: MyUseCases
): ViewModel()

可组合的UI测试类

@HiltAndroidTest
class MyScreenKtTest{

    @get:Rule(order = 0)
    val composeTestRule = createComposableRule()

    @get:Rule(order = 1)
    val hiltTestRule = HiltAndroidRule(this)

    lateinit var navController : TestNavHostController

    @Before
    fun init(){
        hiltTestRule.inject()
    }

    @Test
    fun DemoTestFunction() {
        composeTestRule.setContent {
            navController = TestNavHostController(LocalContext.current)
            MyScreen(myViewModel = myViewModel,navController = navController)
        }
        composeTestRule.onNodeWithText("My name").assertIsDisplayed()
    }

}

错误是
无法创建类MyViewModel的示例
如何在可组合UI测试中注入视图模型?

nqwrtyyt

nqwrtyyt1#

您在init()块中提到了composeTestRule.setContent{}

@Before
fun init(){
    hiltTestRule.inject()
    
      composeTestRule.setContent {
        navController = TestNavHostController(LocalContext.current)
        myViewModel = composeTestRule.activity.viewModels<MyViewModel>().value

        MyScreen(myViewModel = myViewModel,navController = navController)
    }
}

相关问题