I am trying to do some UI testing in isolation on some fragments that uses a shared Bottom navigation view from MainActivity, basically used to navigate and to scroll up and down, but my tests fails with nullpointerException basically because the buttons inside the bottom navigation view are not found in the fragment layout. My question is how to pass these layouts belonging to mainactivity to the fragmentTest class.
Asked
Active
Viewed 915 times
1
-
As abstract as this question is written, it might be difficult to answer. Please add the least code required to reproduce the problem, in case you'd like to see a reliable answer; else I could only close it as duplicate of: [What is a NullPointerException, and how do I fix it?](https://stackoverflow.com/questions/218384/what-is-a-nullpointerexception-and-how-do-i-fix-it) (`FragmentScenario` might be the wrong approach). – Martin Zeitler Dec 24 '19 at 18:36
-
I am trying to use fragment Scenario val scenario = launchFragmentInContainer
( fragmentArgs = null,factory = fragmentFactory) what other choice do i have ? for example i used fab = (activity as? AppCompatActivity)!!.findViewById(R.id.floatingActionButton) to access the fab inside the bottom nav view of the main activity from within the fragment – joghm Dec 24 '19 at 18:43
1 Answers
1
FragmentScenario
is the wrong approach, because a Fragment
should not even depend on the parent Activity
(and if it does, always check with instanceof
or is
, which one Activity
it actually had been attached to). Better instrument the parent Activity
with an ActivityTestRule
instead, because a FragmentScenario
uses it's own mock Activity
and so you'll never get a handle to the expected one parent Activity
(that's intentional, in order to rule out rigid dependencies to the parent Activity
). Just set a break-point inside your current test's code, in order to see that there is no BottomNavigationView
present, because it hasn't been inflated.
There's also a new ActivityScenario
(which is currently still in beta stage).

Martin Zeitler
- 1
- 19
- 155
- 216