launching-fragments-with-fragmentscenario
Installation
SKILL.md
Launching Fragments with FragmentScenario — Test Fragments in Isolation
FragmentScenario hosts a single fragment inside an internal EmptyFragmentActivity so the fragment's onCreate / onViewCreated / lifecycle can be exercised without a real screen. Two entry points exist: launchFragmentInContainer<F>() adds the fragment to android.R.id.content (full lifecycle including view), and launchFragment<F>() attaches it with no container (headless). The default theme extends android:Theme.WithActionBar, NOT AppCompat — overriding via themeResId is required for any AppCompat widget. This skill encodes the two artifacts, the theme trap, and the navigation limitation.
When to use this skill
- The user wants to test a single Fragment without launching the full host Activity.
- A test crashes with
IllegalArgumentException: You need to use a Theme.AppCompat theme (or descendant) with the design libraryand the fragment uses AppCompat / Material widgets. - A test calls
findNavController()and crashes withFragment ... does not have a NavController set. - The user wants to drive lifecycle (
STARTED/RESUMED/DESTROYED) on a fragment for state-change testing. - The user wants to inject a custom
FragmentFactoryfor a fragment that doesn't have a no-arg constructor. - The user mentions "headless fragment" or asks why
onViewCreateddoesn't fire.
When NOT to use this skill
- The host is an Activity, not a Fragment — see
../launching-activities-with-activityscenario/SKILL.md. - The fragment requires a real navigation stack (
NavHostFragment) —FragmentScenariodoes not provide one; use a custom test host activity that wires upNavHostFragmentinstead, orTestNavHostController. - The runner / dependency stack is not yet set up — start with
../../runner/running-instrumented-tests-with-androidjunit4/SKILL.md. - The fragment hosts Compose content and the test interacts via the Compose tree — see
../../../compose/setup/configuring-test-dependencies/SKILL.md.