5

For my test I launch the fragment in an emtpy activity root view container

@Before
fun init() {
    scenario = launchFragmentInContainer(null, R.style.Theme_AppCompat) {
        MyFragment()
    }
}

and in my fragment, I configure the toolbar to provide back button

(activity as AppCompatActivity).setSupportActionBar(binding.toolbar)
(activity as AppCompatActivity).supportActionBar?.setDisplayHomeAsUpEnabled(true)

so when I run my test I get a class cast exception

java.lang.ClassCastException: androidx.fragment.app.testing.FragmentScenario$EmptyFragmentActivity cannot be cast to androidx.appcompat.app.AppCompatActivity

so I have to add a gaurd

if(requireActivity() !is FragmentScenario.EmptyFragmentActivity)
    configureToolBar()    

so is there another way to configure the toolbar so that I can test the back button intent launch with espresso?

edit

Apparently there is a way to create a custom activity/container.

the_prole
  • 8,275
  • 16
  • 78
  • 163
  • What **fragment** behavior are you verifying in your test when you say "is there another way to configure the toolbar so that I can test the back button intent launch with espresso?" - it seems that any espresso test you would be doing there would be verifying the activity, not your fragment. – ianhanniballake May 22 '20 at 01:27
  • I want to verify back navigation from the fragment. – the_prole May 22 '20 at 08:59
  • So what code **of your fragment** is running when you test the up button in your Toolbar? That logic is on the Activity, which isn't what you're testing if you're using `FragmentScenario`. – ianhanniballake May 22 '20 at 15:18
  • you can have toolbar inflated in the Fragment layout and set it as support toolbar by `AppCompatActivity`. Additionally custom handling of up button can be done in the fragment which should be testable with `FragmentScenario` – Kamil Seweryn Sep 07 '20 at 10:15

0 Answers0