【问题标题】:Espresso How to access views without using R.id.viewid as we do in robotium?Espresso 如何在不使用 R.id.viewid 的情况下访问视图,就像我们在 robotium 中所做的那样?
【发布时间】:2015-04-29 14:39:42
【问题描述】:

我正在从robotium 切换到espresso,我正在使用apk 编写测试,我无法访问代码。 在robotium 中使用solo.getView("view-id") 我们可以访问视图,但我不知道如何在espresso 中进行操作? espresso witId() 方法需要我无权访问的 R.id.viewid。

public class AaEspressoTest {

private static final String LAUNCHER_ACTIVITY_FULL_CLASSNAME = "com.tri.re.CordActivity";
private static Class<?> launcherActivityClass;

static {
    try {
        launcherActivityClass = Class.forName(LAUNCHER_ACTIVITY_FULL_CLASSNAME);
    } catch (ClassNotFoundException e) {
        throw new RuntimeException(e);
    }
}

@Rule
public ActivityTestRule<?> mActivityRule = new ActivityTestRule(launcherActivityClass);


@Test public void testHello() throws Exception{

    onView(withText("Browse older recordings")).perform(click());

   //Id is not accessible shows red
    onView(withId(R.id.button)).perform(click());

}

}

【问题讨论】:

标签: android junit4 robotium android-testing android-espresso


【解决方案1】:

您可以使用辅助函数来获取 id:

private static int getId(String id) {
  Context targetContext = InstrumentationRegistry.getTargetContext();
  String packageName = targetContext.getPackageName();
  return targetContext.getResources().getIdentifier(id, "id", packageName);
}

然后你可以在 Espresso 中使用 id:

onView(withId(getId("button"))).perform(click());

【讨论】:

  • 太棒了!!这正是我想要的。非常感谢我的一天.. 荣誉
【解决方案2】:

您可以从命令行使用uiautomator 或打开Android Device MonitorHierarchy Viewer 来转储应用程序的当前可见屏幕,并从每个屏幕视图中获取大量信息,包括资源id,这是您要在测试中使用的视图 ID。

Genynmotion 出于某种原因不显示 id,但使用真实设备或 Android 模拟器应该可以工作。

【讨论】:

    猜你喜欢
    • 2012-03-13
    • 2021-09-02
    • 2018-05-30
    • 2013-10-15
    • 1970-01-01
    • 2021-10-15
    • 1970-01-01
    • 1970-01-01
    • 2012-03-31
    相关资源
    最近更新 更多