使用 Jetpack Compose、dagger hilt 和 JUnit4 测试 Android 应用程序时出现错误

问题描述 投票:0回答:1

我在使用 Jetpack Compose、dagger hilt 和 JUnit4 对 Android 应用程序进行 UI 测试时遇到问题。 我只是想测试一下我的按钮 详细内容如下:

@HiltAndroidTest
@RunWith(AndroidJUnit4::class)
class HomeUITest {
@get:Rule(order = 0)
var hiltRule = HiltAndroidRule(this)

// use createAndroidComposeRule<YourActivity>() if you need access to
// an activity
@get:Rule(order = 1)
val composeTestRule = createComposeRule()

lateinit var loginViewModel: LoginViewModel

@Before
fun setUp() {
    hiltRule.inject()

    composeTestRule.setContent {
        DanamonAppTheme {
            LoginPageScreen()
        }
    }
}

@Test
fun myUIComponentTest() = runTest {

    composeTestRule.onNodeWithText("Login").performClick()

}
}

当我运行测试类时,出现错误 ->

Hilt test, com.kelvin.pastisystem.HomeUITest, cannot use a @HiltAndroidApp application 
but found com.kelvinquantic.danamon.MainApplication. To fix, configure the test to use 
HiltTestApplication or a custom Hilt test application generated with 
@CustomTestApplication.

我已将 @HiltAndroidApp 注释添加到我的主应用程序类中,就像这样 ->

@HiltAndroidApp
class MainApplication : Application() {
...

我已经尝试了博客和chatGPT的一些解决方案,但没有找到好的解决方案,请帮助。谢谢您的关注

android testing android-jetpack-compose dagger dagger-hilt
1个回答
0
投票

我使用此方法初始化视图模型。 您可以使用此方法来初始化 viewModel。 希望您的问题能够得到解决。

@OptIn(ExperimentalCoroutinesApi::class)
class RegisterViewModelTest {
private val registerUseCase: RegisterUseCase = mock()
private val getCountriesUseCase: GetCountriesUseCase = mock()
private val getJobsUseCase: GetJobsUseCase = mock()

@OptIn(DelicateCoroutinesApi::class)
private val mainThreadSurrogate = newSingleThreadContext("UI thread")

@Before
fun setUp() {
    Dispatchers.setMain(mainThreadSurrogate)
}

@After
fun tearDown() {
    Dispatchers.resetMain() // reset the main dispatcher to the original Main 
       dispatcher
    mainThreadSurrogate.close()
}

@Test
fun `onExpertise adds expertise to the list`(): Unit = runBlocking {
    launch {
        val vm: RegisterViewModel = RegisterViewModel(registerUseCase, 
        getCountriesUseCase, getJobsUseCase)
        val expertise = Expertise(id = 1, name = "Test Expertise")

        // When
        vm.onTriggerEvent(RegisterUiEvent.OnExpertise(expertise))

        // Then
        assert(vm.uiState.value.data.expertises?.contains(expertise) == true)
    }
}

}

© www.soinside.com 2019 - 2024. All rights reserved.