2017-04-19 87 views
1

我试图用新的android-test-kit(Espresso)写一些测试。但我找不到任何关于如何检查视图是否显示的信息,并对其执行一些操作(如单击按钮,e.t.c.)。请注意,我需要检查它是否存在的视图。如果它确实在视图上执行操作,并且如果不执行到下一个视图。咖啡 - 检查屏幕是否可见

任何帮助,将不胜感激。我只是需要一个链接,或者一些示例代码为基础:

检查认为存在 如果是,如果没有执行动作 ,继续下一屏幕

回答

1

您可以使用一个经典的选项“尝试/ catch“:

try { 
    onView(withText("Text")).check(matches(isDisplayed())); 
    //perform some actions on this view 
} catch (NoMatchingViewException notExist) { 
    //proceed to the next screen 
} 
1

您必须控制测试的行为。所以,你必须添加一些先决条件,或者创建一个可以控制行为的@Rule,例如通过添加参数取决于你的视图的显示与否。

2
Object currentActivity; 

@Nullable 
private Activity getCurrentActivity() throws Throwable { 
    getInstrumentation().waitForIdleSync(); 
    getInstrumentation().runOnMainSync(new Runnable() { 
     public void run() { 
      Collection resumedActivities = ActivityLifecycleMonitorRegistry.getInstance().getActivitiesInStage(RESUMED); 
      if (resumedActivities.iterator().hasNext()) { 
       currentActivity = resumedActivities.iterator().next(); 
      } 
     } 
    }); 

    return (Activity) currentActivity; 
} 

与此,您可以获取当前显示的活动。之后,通过做这样的事情,你可以做一个安全的代码段

HOMESCREEN: 
     { 
      for (; ;) { 
       if (getCurrentActivity() != null) { 
        //check if it is the required screen 
        if (getCurrentActivity().getLocalClassName().toLowerCase().contains("homescreen")) { 
         //if it is the required screen, break the 
         //loop and continue execution 
         break HOMESCREEN; 
        } else { 
         //wait for 2 seconds and run the loop again 
         sleep(2000); 
        } 
       } else { 
        break HOMESCREEN; 
       } 
      } 
     } 

睡眠(2000)是只是调用了Thread.Sleep如下所示的自定义函数:

private void sleep(long milliseconds) { 
    try { 
     Thread.sleep(millis); 
    } catch (InterruptedException e) { 
     throw new RuntimeException("Cannot execute Thread.sleep()"); 
    } 
}