gpt4 book ai didi

android - 如何使用 Espresso 测试 fragment

转载 作者:塔克拉玛干 更新时间:2023-11-01 21:26:42 25 4
gpt4 key购买 nike

我有一个要测试的 Android fragment 。我创建了一个测试 Activity ,我向其中添加了这个 fragment 并运行了一些 Espresso 测试。

但是,Espresso 在 fragment 中找不到任何 View 。它会转储 View 层次结构,并且全部为空。

我不想使用实际的父 Activity 。我只想单独测试这个 fragment 。有没有人这样做过?是否有具有类似代码的示例?

@RunWith(AndroidJUnit4.class)
class MyFragmentTest {
@Rule
public ActivityTestRule activityRule = new ActivityTestRule<>(
TestActivity.class);

@Test
public void testView() {
MyFragment myFragment = startMyFragment();
myFragment.onEvent(new MyEvent());
// MyFragment has a recyclerview.
//OnEvent is EventBus callback that in this test contains no data.
//I want the fragment to display empty list text and hide the recyclerView
onView(withId(R.id.my_empty_text)).check(matches(isDisplayed()));
onView(withId(R.id.my_recycler)).check(doesNotExist()));
}

private MyFragment startMyFragment() {
FragmentActivity activity = (FragmentActivity) activityRule.getActivity();
FragmentTransaction transaction = activity.getSupportFragmentManager().beginTransaction();
MyFragment myFragment = new MyFragment();
transaction.add(myFragment, "myfrag");
transaction.commit();
return myFragment;
}
}

最佳答案

我会按照以下方式做创建一个 ViewAction,如下所示:

public static ViewAction doTaskInUIThread(final Runnable r) {
return new ViewAction() {
@Override
public Matcher<View> getConstraints() {
return isRoot();
}

@Override
public String getDescription() {
return null;
}

@Override
public void perform(UiController uiController, View view) {
r.run();
}
};
}

然后使用下面的代码来启动应该在 UI 线程中运行的代码

onView(isRoot()).perform(doTaskInUIThread(new Runnable() {
@Override
public void run() {
//Code to add your fragment or anytask that you want to do from UI Thread
}
}));

下面是添加 fragment View 层级的测试用例示例

    @Test
public void testSelectionOfTagsAndOpenOtherPage() throws Exception{

Runnable r = new Runnable() {
@Override
public void run() {
//Task that need to be done in UI Thread (below I am adding a fragment)

}
};
onView(isRoot()).perform(doTaskInUIThread(r));

}

关于android - 如何使用 Espresso 测试 fragment ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35471425/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com