2017-05-04 9 views
0

내 Android 활동의 메뉴가 동적으로 채워지고 항목을 에스프레소로 표시하는지 테스트하고 싶습니다. 나는 "M"를 포함하는 제목 문자열 일부 제목 문자열 "N"적어도 1 항목, 예를 들면 :에스프레소와 함께 "조건이있는 뷰를 적어도 하나 이상"으로 주장하는 방법?

  • 항목 N1
  • 항목 N2
  • 를 포함하는 제목으로 적어도 1 항목이있을 것을 알고있다
  • 항목 M1
  • 항목 M2
  • 나는 시험 AmbiguousViewMatcherException 예외 얻고있다

:

openActionBarOverflowOrOptionsMenu(getInstrumentation().getTargetContext()); 

    // go to subitem level 1 
    onView(
     allOf(
      withId(R.id.title), 
      withText("Settings"), 
      isDisplayed())) 
       .perform(click()); 
    SystemClock.sleep(50); 

    // go to subitem level 2 
    onView(
     allOf(
      withId(R.id.title), 
      withText("Item type"), 
      isDisplayed())) 
       .perform(click()); 
    SystemClock.sleep(50); 

    // items are shown 

    // assertions 
    onView(
     allOf(withId(R.id.title), 
      withText("N"), 
      isDisplayed())) 
       .check(matches(isDisplayed())); 

    onView(
     allOf(withId(R.id.title), 
      withText("M"), 
      isDisplayed())) 
       .check(matches(isDisplayed())); 

올바른 어설 션 의미는 다음과 같습니다. "다음 제목이 포함 된보기가 적어도 1 개 있습니다 ("제목이 ... "이라고 가정 해 봅시다)?"

나는 예외를 잡을 수 있다는 것을 알고 있으며 실제로 테스트가 통과되었다는 것을 의미하지만 나는 그 일을 올바르게하고 싶습니다.

답변

1

내가 아는 한 에스프레소에서는 그렇게 쉽지 않습니다. 일치하는보기 중 하나를 가져와 확인을 수행하려면 사용자 지정 일치 프로그램을 사용해야합니다.

그래서 당신이 사용자 정의 정규 표현을 사용하는 경우 :

public static Matcher<View> withIndex(final Matcher<View> matcher, final int index) { 
    return new TypeSafeMatcher<View>() { 
     int currentIndex = 0; 

     @Override 
     public void describeTo(Description description) { 
      description.appendText("with index: "); 
      description.appendValue(index); 
      matcher.describeTo(description); 
     } 

     @Override 
     public boolean matchesSafely(View view) { 
      return matcher.matches(view) && currentIndex++ == index; 
     } 
    }; 
} 

는 다음과 같은 텍스트 "M"과 함께 첫 번째보기를 확인할 수 있습니다 :

withIndex(allOf(withId(R.id.title), withText("M"), 
      isDisplayed())), 0) 
      .matches(isDisplayed()); 

이 코드는 여기에서 가져온 것입니다 https://stackoverflow.com/a/39756832/2567799합니다. 또 다른 옵션은 첫 번째 요소를 반환한다는 정규 표현식을 작성하는 것입니다. 이 던져 있지 않다면 내 특정 경우

0

나는 예외를 잡을 실패하기로 결정

try { 
    onView(
     allOf(
      withId(R.id.title), 
      withText(containsString("N")), 
      isDisplayed())) 
     .check(matches(isDisplayed())); 
    fail("We should have multiple suitable items, so AmbiguousViewMatcherException exception should be thrown"); 
} catch (AmbiguousViewMatcherException e) { 
    // that's ok - we have multiple items with "N" in the title 
} 
+1

내가 대신 예외를 잡는 아래 설명과 같이 사용자 정의 정규를 사용하는 것이 좋습니다. 이 정규 표현자가 사용자의 설명과 일치하는 첫 번째 요소를 반환하는 동안 예외의 원인을 완전히 확신 할 수 없습니다. 따라서 실제로 일치하는 뷰 요소가 있는지 확인할 수 있습니다. 또한 예외를 잡는 것은 분명히 깨끗한 코드가 아니기 때문에 이러한 논리 흐름을 제어하기위한 것은 아닙니다. – stamanuel