android-fragments – 为什么当我尝试从Android Test中的fragmentManager获取片段时,我得到NullPointerException?

你好,我是
Android测试的新手.在UI测试期间,我试图检查我的应用程序中是否有可见的按钮.我写了一些东西:

@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());
}

在线

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

我得到NullPointerException.它看起来像一个片段没有加载.但我不知道为什么.但是,当我尝试单击该片段中的按钮时,它可以正常工作:

onView(withId(R.id.orderOpenRegister)).perform(click());

我想做的事情如下:

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

此按钮位于current_order_fragment中,其ID为orderOpenRegister.

编辑

我发现,我应该添加以下行:

fragmentManager.executePendingTransactions();

所以我的方法看起来像:

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;
}

但如果我这样做,我需要在UI线程中运行此测试.有谁知道如何在UI线程上运行测试?

最佳答案 您可以在UI线程中运行测试,如下所示

Instrumentation instrumentation = InstrumentationRegistry.getInstrumentation();

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