1 year ago

#382088

test-img

Aanal Shah

Android Unit test: Error: EmptyFragmentActivity cannot be cast to BaseActivity. How to get Instance of an Activity which is not defined in Manifest?

I am new to writing Android Test Cases. I am trying to write a test case for a project which is already developed. It has so many Activities and Fragments and we are using Navigation Graph for navigating the fragments.

I have started writing test cases from the first fragment and the code is as below:

val navController = TestNavHostController(ApplicationProvider.getApplicationContext())

val scenario = launchFragmentInContainer<SplashFragment>()
scenario.onFragment{
    // Get Auth Navigation
    navController.setGraph(R.navigation.auth_navigation)
    Navigation.setViewNavController(it.requireView(), navController)
    it.redirectUser()
}

Now my SplashFragment contains few methods which have checks like

fun getAppName(): String {
    return (activity as BaseActivity).getAppName()
}

Here, the BaseActivity is the activity which extends AppCompatActivity and it is not defined in my AndroidManifest file.

When I execute the test, I am getting an exception like:

androidx.fragment.app.testing.FragmentScenario$EmptyFragmentActivity cannot be cast to com.xxx.ui.base.BaseActivity

Can anyone please help me with this?

android

junit4

android-testing

android-instrumentation

android-unit-testing

0 Answers

Your Answer

Accepted video resources