gpt4 book ai didi

java - 带有 fragment 的 Android Espresso 功能测试

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

我的应用程序中有三个 Activity

  1. 登录 Activity
  2. 一项主要 Activity
  3. 详细 Activity

我想使用 espresso 测试一系列事件:单击登录 Activity 上的登录按钮,这会打开主 Activity ,然后单击主 Activity 中的列表项,这会打开详细 Activity ,然后单击另一个按钮在详细 Activity 中。我首先创建了这个简单的测试,以获取对 ListView 的引用:

public class LoginActivityTest extends ActivityInstrumentationTestCase2<LoginActivity> {

public LoginActivityTest() {
super(LoginActivity.class);
}

@Override
public void setUp() throws Exception {
super.setUp();

getActivity();
}

public void testSequence() throws Exception {
// Login
onView(withId(R.id.button_log_in)).perform(click());

// Check if MainActivity is loaded
onView(withId(R.id.container)).check(matches(isDisplayed()));

// Check if Fragment is loaded
onView(withId(R.id.list)).check(matches(isDisplayed()));
}
}

ma​​inActivity onCreate() 方法上,我加载了这样一个 fragment :

getFragmentManager().beginTransaction()
.add(R.id.container, mListFragment)
.commit();

ListFragment fragment 有一个列表 (R.id.list),但测试仍然失败并出现 NoMatchingViewException:

android.support.test.espresso.NoMatchingViewException: No views in hierarchy found matching: with id: com.tests.android.development:id/list

我做错了什么?

最佳答案

来自 documentation 的注释对于 onView:

Note: the view has to be part of the view hierarchy. This may not be the case if it is rendered as part of an AdapterView (e.g. ListView). If this is the case, use Espresso.onData to load the view first.

要使用 onData 加载 View ,您需要检查 ListView 中的适配器实例。换句话说,如果您的 ListView 使用 Cursor 适配器,您可以试试这个:

onData(allOf(is(instanceOf(Cursor.class)))).check(matches(isDisplayed()));

重要的是要注意,只有当您的 ListView 包含至少一项时,以上内容才会通过。最好在项目存在的地方进行一次测试,在项目不存在的地方进行一次测试。

有关如何检查确实存在的数据的更多信息,请参阅 here .

有关如何检查适配器中不存在的数据的更多信息,请参阅 here .

关于java - 带有 fragment 的 Android Espresso 功能测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28455196/

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