我现在看到了一些你尝试使用 hilt 导航注入 viewModel 的情况,但它给出了错误。
我有一个抽象 viewModel,它被 5 个不同的 viewmodel 继承,并且 viewModel 的作用域为 backstack。 在模拟器和真实设备上一切正常,只是在 UI 测试中不行。
这是抽象视图模型:
abstract class ProposeNewGoalViewModel : ViewModel() {
private val proposedGoalUiDataInit = ProposedGoalUiData(
targetAmount = null,
startYear = LocalDateTime.now().year.toString(),
singleOrRecurring = SingleOrRecurring.SINGLE,
goalName = null,
wantWishOrNeed = WantWishOrNeed.NEED,
yearCareProvidedStart = LocalDateTime.now().year.toString()
)
open fun resetState() {
......
}
//methods
.......
}
这是视图模型之一:
@HiltViewModel
class Category1OneTimeOrRecurringViewModel @Inject constructor() : ProposeNewGoalViewModel() {
override fun resetState() {
super.resetState()
showRecurrenceFormFields.update { false }
onTargetAmountChanged("")
onStartYearChanged("")
onFrequencyChanged("")
onNumberOfOccurrencesChanged("")
}
}
所以没有什么惊天动地的事情。 这是我在 androidTest 中收到错误的地方:
@AndroidEntryPoint
class GoalsFragment() {
@AndroidEntryPoint
class GoalsFragment : BaseFragment() {
.......
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
return ComposeView(requireActivity()).apply {
setViewCompositionStrategy(ViewCompositionStrategy.DisposeOnViewTreeLifecycleDestroyed)
setContent {
GoalsNav(
goalsViewModel = goalsViewModel,
proposeNewGoalViewModel = proposeNewGoalScreenViewModel,
popBackStack = { activity?.finish() },
navigateToAccounts = {
landingViewModel.performNavigationSubject.onNext(R.id.accounts)
},
navigateToMyTeamMessage = { messageType ->
findNavController().navigateSafe(
R.id.action_goalsLanding_to_myTeamNewMessage,
MyTeamNewMessageFragmentArgs(
messageType
).toBundle()
)
},
fragmentNavController = findNavController()
)
}
}
}
}
@SuppressLint("NavigateSafe")
@Composable
fun GoalsNav(
goalsViewModel: GoalsViewModel,
proposeNewGoalViewModel: ProposeNewGoalScreenViewModel,
navController: NavHostController = rememberNavController(),
popBackStack: () -> Unit,
navigateToAccounts: () -> Unit,
navigateToMyTeamMessage: (MyTeamMessageType) -> Unit,
fragmentNavController: NavController
) {
EJTheme {
NavHost(
navController = navController,
startDestination = GOALS_ROUTE
) {
////////////////////THIS WORKS FINE IN TEST
composable(route = PROPOSE_NEW_GOAL_ROUTE) { backStackEntry ->
ProposeNewGoalScreen(
viewModel = hiltViewModel<ProposeNewGoalScreenViewModel>(backStackEntry),
navigateBack = { navController.popBackStack() },
onNavigateToGoalType = {
navController.navigate(
"$FILL_OUT_PROPOSED_NEW_GOAL_ROUTE/${it.goalType}"
)
},
)}
/////////////////ILLEGAL STATE
composable(route = "$FILL_OUT_PROPOSED_NEW_GOAL_ROUTE/{$PROPOSE_GOAL_TYPE_ARG}") { backStackEntry ->
val goalTypeArg =
backStackEntry.arguments?.getString(PROPOSE_GOAL_TYPE_ARG)?.toInt()
val selectedGoalTypeEnum = goalTypeArg?.let { GoalType.getGoal(it) }
val proposeNewGoal = selectedGoalTypeEnum?.let { ProposeNewGoal.getGoalBasedOnGoalType(it) }
val proposeNewGoalViewModelForForm = when (proposeNewGoal?.category) {
Category.CATEGORY_1_SINGLE_OR_REOCCURRING -> {
hiltViewModel(backStackEntry) as Category1OneTimeOrRecurringViewModel. ///////error happens here
}
Category.CATEGORY_2_EDUCATION -> {
hiltViewModel(backStackEntry) as Category2EducationViewModel
}
Category.CATEGORY_3_SINGLE_OCCURRENCE -> {
hiltViewModel(backStackEntry) as Category3SingleTimeViewModel
}
Category.CATEGORY_4_PROVIDE_CARE -> {
hiltViewModel(backStackEntry) as Category4ProvideCareViewModel
}
Category.CATEGORY_5_BEQUEST -> {
hiltViewModel(backStackEntry) as Category5LeaveBequestViewModel
}
null -> hiltViewModel(backStackEntry) as Category1OneTimeOrRecurringViewModel
}
ProposeNewGoalForm(
viewModel = proposeNewGoalViewModelForForm,
navigateBack = { navController.navigate(PROPOSE_NEW_GOAL_ROUTE) { popUpTo(PROPOSE_NEW_GOAL_ROUTE) { inclusive = true } } },
onNavigateBackToGoals = navigateToGoals,
validateForm = {
proposeNewGoalViewModelForForm.validateForm()
},
selectedGoalType = goalTypeArg,
onNavigateToConfirmation = { navController.navigate("$FILL_OUT_PROPOSED_NEW_GOAL_ROUTE_CONFIRMATION/$goalTypeArg") },
)
}
}
}
我尝试使抽象类成为一个带有 HiltViewModel 且没有骰子的开放类。 我认为这是一个错误。
测试设置
@HiltAndroidTest
class ProposeNewGoalNavigationTests {
lateinit var navController: TestNavHostController
@get:Rule
val composeTestRule = createComposeRule()
private val context: Context
get() = ApplicationProvider.getApplicationContext()
private val goalsRepository: GoalsRepo = mock()
private val featureTogglesRepo: FeatureTogglesRepo = mock()
private val userDataRepo: UserDataRepo = mock()
private val staticContentRepo: StaticContentRepository = mock()
private val analyticRepository: AnalyticsRepo = mock()
private val documentsRepo: DocumentsRepo = mock()
private val messagesRepository: MyTeamMessagesRepository = mock()
private val documentUseCase = DocumentDownloadUseCase(
documentsRepo,
mock(),
"EJFileAbsolutePath"
)
private val launchDarklyFlagsRepo: LaunchDarklyFlagsRepo = mock()
@get:Rule
val setupRepoRule = SetupRepoRule()
@get:Rule
var hiltRule = HiltAndroidRule(this)
@Mock
val dispatcherProvider: DispatcherProvider = Mockito.mock()
val goalsRepo: GoalsRepo = mock()
@BindValue
val proposeNewGoalScreenViewModel = ProposeNewGoalScreenViewModel()
@BindValue
val confirmVM = ConfirmNewProposedGoalViewModel(
goalsRepository = goalsRepository,
userDataRepo = userDataRepo,
featureTogglesRepo = featureTogglesRepo,
messagesRepository = messagesRepository,
dispatcherProvider = dispatcherProvider
)
@BindValue
val category1FormVM = Category1OneTimeOrRecurringViewModel()
@BindValue
val category2FormVM = Category2EducationViewModel()
@BindValue
val category3FormVM = Category3SingleTimeViewModel()
@BindValue
val category4FormVM = Category4ProvideCareViewModel()
@BindValue
val category5FormVM = Category5LeaveBequestViewModel()
@Before
fun setupNavHost() {
hiltRule.inject()
val goalViewModel = GoalsViewModel(
goalsRepository = goalsRepository,
featureTogglesRepo = featureTogglesRepo,
userDataRepo = userDataRepo,
savedStateHandle = SavedStateHandle(mapOf(GoalsViewModel.ON_TRACK_CALCULATED to false)),
dispatcher = Dispatchers.IO,
analyticsRepository = analyticRepository,
staticContentRepo = staticContentRepo,
documentDownloadUseCase = documentUseCase,
launchDarklyFlagsRepo = launchDarklyFlagsRepo
)
composeTestRule.setContent {
navController =
TestNavHostController(LocalContext.current)
navController.navigatorProvider.addNavigator(DialogNavigator())
navController.navigatorProvider.addNavigator(ComposeNavigator())
GoalsNav(
goalsViewModel = goalViewModel,
proposeNewGoalViewModel =
proposeNewGoalScreenViewModel,
navController = navController,
popBackStack = {},
navigateToAccounts = {},
navigateToMyTeamMessage = {},
fragmentNavController = rememberNavController()
)
}
}
}
对于那些正在寻找答案的人:
我通过执行以下操作解决了这个问题:添加 HiltComponentActivity 进行调试并将其添加到调试清单中:
HiltComponentActivity:
@AndroidEntryPoint
class HiltComponentActitivity: ComponentActivity
然后在我的测试中:
@get:Rule val composeTestRule = createAndroidComposeRule<HiltComponentActivity>()