Error when UI Testing Android Apps using Jetpack Compose, dagger hilt and JUnit4

47 Views Asked by At

I've Issue when UI Testing an android app using Jetpack Compose, dagger hilt and JUnit4. I'm just want to test tap on my button here's the detail:

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

}
}

when i run the test class, i got error ->

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.

i've add @HiltAndroidApp annotation to my Main Application class, just like this ->

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

i've tried some solution from blogs and chatGPT but not found good solution, please help. thankyou for your attention

1

There are 1 best solutions below

0
mahdi asd On

I initialize the viewmodel using this method. You can use this method to initialize the viewModel. I hope your problem will be resolved.

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

}