11

I am doing some Espresso testing in Android. The test is failing with this error:

java.lang.ClassCastException: androidx.fragment.app.testing.FragmentScenario$EmptyFragmentActivity cannot be cast to com.stavro_xhardha.pockettreasure.MainActivity

This is my test method:

@Test
fun toolbarTitle_shouldContainCorrectInput() {
    val mockNavController = mock(NavController::class.java)
    val fragmentScenario = launchFragmentInContainer<SetupFragment>()
    fragmentScenario.onFragment {
        Navigation.setViewNavController(it.view!! , mockNavController)
    }
    onView(withId(R.id.toolbar)).check(matches(withText("Pick your country")))
}

But the error doesn't come from the Test class but from my Fragment under test. The crash is executed in this line of code:

override fun onStart() {
    super.onStart()
    (activity!! as MainActivity).supportActionBar?.hide() //here
}

What I don't get here is that I face no error when I run the app normally without test.

coroutineDispatcher
  • 7,718
  • 6
  • 30
  • 58
  • This means that your `activity` is an `EmptyFragmentActivity` and you try to cast it to `MainActivity` – Dmitriy Mitiai May 28 '19 at 08:38
  • what's an `EmptyFragmentActivity` – coroutineDispatcher May 28 '19 at 08:44
  • 1
    Did you read the documentation about the `launchFragmentInContainer`? All that this functionality does it take the given fragment and launch it inside of an internal EmptyFragmentActivity class — placing the fragment inside of the root view container – Dmitriy Mitiai May 28 '19 at 08:59

2 Answers2

23

Here is the full answer.
About launchFragmentInContainer - it takes the given fragment and launches it inside of an internal EmptyFragmentActivity class — placing the fragment inside of the root view container.
So, it should be used to check fragment only, which doesn't depend on it's parent activity.

In your case, you try to hide an action bar inside the fragment you're testing. But in test your fragment will not be launched in MainActivity.
If you want to check only the fragment, instead of (activity!! as MainActivity).supportActionBar?.hide() you need to write something like this:

if(activity!! is MainActivity){
    activity?.supportActionBar?.hide()
}

Or you should write the test for your MainActivity or where you use your fragment

Prabindh
  • 3,356
  • 2
  • 23
  • 25
Dmitriy Mitiai
  • 1,112
  • 12
  • 15
1

Hiding the ActionBar helped in my case.

  if (activity is AppCompatActivity) {
                (activity as AppCompatActivity).supportActionBar?.hide()
  }