您好我是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());
}
在线
查看v = f.getView(); //在方法isRegisterClosed()
中
我得到NullPointerException。它看起来像一个片段没有加载。但我不知道为什么。但是,当我尝试单击该片段中的按钮时,它可以工作:
onView(withId(R.id.orderOpenRegister))执行(点击());
我想做类似的事情:
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线程上运行测试?
答案 0 :(得分:2)
您可以在UI线程中运行测试,如下所示
Instrumentation instrumentation = InstrumentationRegistry.getInstrumentation();
instrumentation.runOnMainSync(new Runnable() {
@Override
public void run() { //your test
}
});