2016-07-22 59 views
1

我們可以通過Espresso獲得當前的展示活動來相應地寫下一些條件代碼嗎?Espresso獲取展示活動

在我的應用程序中,我們有一個簡介頁面,只顯示用戶一次從下一個應用程序直接將用戶登錄屏幕。我們可以檢查用戶登陸哪個屏幕,因此我們可以相應地寫下我們的測試用例。

回答

1

您可以在我們必須檢查的佈局中放入一個唯一的ID。在這個例子中,你描述的,我會把在登錄佈局:

<RelativeLayout ... 
    android:id="@+id/loginWrapper" 
... 

然後,在測試中,你只需要檢查這個ID顯示:

onView(withId(R.id.loginWrapper)).check(matches(isCompletelyDisplayed())); 

我不知道是否有是一個更好的方法,但這個工程。

而且你還可以等待一段時間與waitId方法,你可以在網上找到:

/** 
* Perform action of waiting for a specific view id. 
* <p/> 
* E.g.: 
* onView(isRoot()).perform(waitId(R.id.dialogEditor, Sampling.SECONDS_15)); 
* 
* @param viewId 
* @param millis 
* @return 
*/ 
public static ViewAction waitId(final int viewId, final long millis) { 
    return new ViewAction() { 
     @Override 
     public Matcher<View> getConstraints() { 
      return isRoot(); 
     } 

     @Override 
     public String getDescription() { 
      return "wait for a specific view with id <" + viewId + "> during " + millis + " millis."; 
     } 

     @Override 
     public void perform(final UiController uiController, final View view) { 
      uiController.loopMainThreadUntilIdle(); 
      final long startTime = System.currentTimeMillis(); 
      final long endTime = startTime + millis; 
      final Matcher<View> viewMatcher = withId(viewId); 

      do { 
       for (View child : TreeIterables.breadthFirstViewTraversal(view)) { 
        // found view with required ID 
        if (viewMatcher.matches(child)) { 
         return; 
        } 
       } 

       uiController.loopMainThreadForAtLeast(50); 
      } 
      while (System.currentTimeMillis() < endTime); 

      // timeout happens 
      throw new PerformException.Builder() 
       .withActionDescription(this.getDescription()) 
       .withViewDescription(HumanReadables.describe(view)) 
       .withCause(new TimeoutException()) 
       .build(); 
     } 
    }; 
} 

有了這個方法,你可以,例如做:

onView(isRoot()).perform(waitId(R.id.loginWrapper, 5000)); 

而這樣的測試將如果登錄屏幕需要5秒或更少時間,則不會失敗。

0

在我Espresso測試類,我用ActivityTestRule,因此要獲得當前活動我用

mRule.getActivity() 

這裏是我的示例代碼:

@RunWith(AndroidJUnit4.class) 
@FixMethodOrder(MethodSorters.NAME_ASCENDING) 
public class SettingsActivityTest { 

    @Rule 
    public ActivityTestRule<SettingsActivity> mRule = new ActivityTestRule<>(SettingsActivity.class); 

    @Test 
    public void checkIfToolbarIsProperlyDisplayed() throws InterruptedException { 
     onView(withText(R.string.action_settings)).check(matches(withParent(withId(R.id.toolbar)))); 
     onView(withId(R.id.toolbar)).check(matches(isDisplayed())); 

     Toolbar toolbar = (Toolbar) mRule.getActivity().findViewById(R.id.toolbar); 
     assertTrue(toolbar.hasExpandedActionView()); 
    } 
} 

希望這將有助於