为什么我在Android测试中尝试从fragmentManager获取fragment时会出现NullPointerException?

4

你好,我是一名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(); // 在 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线程上运行测试吗?

1个回答

3
您可以按照以下方式在UI线程中运行测试。
Instrumentation instrumentation = InstrumentationRegistry.getInstrumentation();

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接