Why am I getting a NullPointerException when I try to get a fragment from a fragmenter in Android Test?

Hi, I am new to Android testing. I tried to check if the button is displayed in the application during the user interface test. I am writing something:

@RunWith(AndroidJUnit4.class)
public class MainActivityTest {
@Rule
public ActivityTestRule<MainActivity> mRule = new ActivityTestRule<>(MainActivity.class);

@Before
public void setUp() {
}

@Test
public void clickOnProductTest() {
    if (isRegisterClosed()) {
        openRegister();
    }
    onView(withText("Food")).perform(click());
    onView(withText("Mineral water")).perform(click());
}

private boolean isRegisterClosed() {
    MainActivity activity = mRule.getActivity();
    FragmentManager fragmentManager = activity.getFragmentManager();

    Fragment f = fragmentManager.findFragmentById(R.id.current_order_fragment);

    View v = f.getView();

    Button b = (Button) v.findViewById(R.id.orderOpenRegister);
    return b.getVisibility() == View.VISIBLE;
}

private void openRegister() {
    onView(withId(R.id.orderOpenRegister)).perform(click());
}

In line

View v = f.getView (); // in the isRegisterClosed () method

I get a NullPointerException. It seems that the fragment did not load. But I do not know why. But when I try to click on the button in this fragment, it works:

OnView (withId (R.id.orderOpenRegister)) execute (click ()) ;.

I want to do something like:

if (buttonIsVisible) {
      do smth;
}
else {
      do smth else;
}

This button is located in current_order_fragment, and its identifier is OrderOpenRegister.

Edit

I will find out that I have to add the following line:

fragmentManager.executePendingTransactions ();

so my method looks like this:

private boolean isRegisterClosed() {
        FragmentManager fragmentManager = activity.getFragmentManager();
        fragmentManager.executePendingTransactions();
        Fragment f  = fragmentManager
                      .findFragmentById(R.id.current_order_fragment);
        View v = f.getView();
        Button b = (Button) v.findViewById(R.id.orderOpenRegister);
        return b.getVisibility() == View.VISIBLE;
}

, . - , ?

+4
1

,

Instrumentation instrumentation = InstrumentationRegistry.getInstrumentation();

instrumentation.runOnMainSync(new Runnable() {
  @Override
  public void run() { //your test
  }
});
+2

All Articles