![](/img/trans.png)
[英]What is the proper way to navigate from ViewModel in Jetpack Compose + Hilt + ViewModel?
[英]Please help - Jetpack Compose Testing - Hilt - ViewModel - Repository
我正在嘗試學習如何使用 Jetpack Compose 進行測試,但我感到迷茫。 我不確定我做錯了什么。 我想測試 MainScreen,但它嵌套在 ScreenNavigation() 中,需要一個 ViewModel 和一個 NavController。 我真的很困惑這是如何工作的。 它告訴我它找不到活動。 我不確定在 AndroidManifest 文件中要做什么。 很感謝任何形式的幫助!
錯誤:android.content.ActivityNotFoundException:無法找到顯式活動 class {com.samm.brewerysearch.test/androidx.test.core.app.InstrumentationActivityInvoker$BootstrapActivity}; 您是否在 AndroidManifest.xml 中聲明了此活動,或者您的意圖與其聲明的不匹配?
<?xml version="1.0" encoding="utf-8"?>
<manifest
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools">
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.CALL_PHONE"/>
<application
android:name="com.samm.brewerysearch.BrewApplication"
android:allowBackup="true"
android:dataExtractionRules="@xml/data_extraction_rules"
android:fullBackupContent="@xml/backup_rules"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/Theme.Bloomberg"
tools:targetApi="31">
<activity
android:name="com.samm.brewerysearch.MainActivity"
android:exported="true"
android:theme="@style/Theme.Bloomberg">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
@HiltAndroidTest
@UninstallModules(AppModule::class)
class MainScreenTest {
@get:Rule(order = 0)
val hiltRule = HiltAndroidRule(this)
@get:Rule(order = 1)
val composeRule = createAndroidComposeRule<MainActivity>()
@Before
fun setUp() {
hiltRule.inject()
composeRule.setContent {
val navController = rememberNavController()
BreweryTheme {
NavHost(
navController = navController,
startDestination = Screens.MainScreen.name
){
composable(Screens.MainScreen.name){
MainScreen(
navController = navController,
mainViewModel = hiltViewModel(),
search = Constants.DEFAULT_CITY
)
}
}
}
}
}
@Test
fun myTest(){
composeRule.onNodeWithText(Constants.DEFAULT_CITY).assertIsDisplayed()
}
}
添加這些規則來測試你的屏幕和模擬 viremodel
@get:Rule
val initRule: MockitoRule = MockitoJUnit.rule()
@get:Rule
val composeTestRule = createAndroidComposeRule<ComponentActivity>()
@Mock
lateinit var mainViewModel: MainViewModel
您可以通過以下方式初始化您的導航控制器
this.navController = rememberNavController()
此外,無需將@HiltAndroidTest
注釋添加到您的 class 中,將此注釋替換為@RunWith(MockitoJUnitRunner::class)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.