EarlGrey
文档指出:
您必须缩小选择范围,直到它能够唯一地识别单个UI元素。
我在我的UI上有三个UIView,我需要使用grey_sufficientlyVisible()
断言检查它们的可见性。但是,除非我逐个使用它们的个别可访问标签或其他方式拾取每个UIView,否则我无法匹配所有UIView。是否有一种方法可以匹配超集合的视图,或者我应该为每个视图创建单独的测试条件?
EarlGrey
文档指出:
您必须缩小选择范围,直到它能够唯一地识别单个UI元素。
我在我的UI上有三个UIView,我需要使用grey_sufficientlyVisible()
断言检查它们的可见性。但是,除非我逐个使用它们的个别可访问标签或其他方式拾取每个UIView,否则我无法匹配所有UIView。是否有一种方法可以匹配超集合的视图,或者我应该为每个视图创建单独的测试条件?
不管怎样,你想要实现的目标可以通过以下几种方式实现:
1)如果所有这些视图都共享一个公共父视图,则可以编写自定义匹配器以匹配父视图,并编写自定义断言来迭代子视图,存储具有所需辅助功能标签的视图,然后将每个单独的视图运行到可见性匹配器中。例如:
for (UIView *view in matchedViews) {
GREYAssertTrue([grey_sufficientlyVisible() matches:view],
@"View %@ is not visible", view);
}
2)或者,如果您不介意创建一个更复杂的匹配多个视图的技术,并且您可以将其创建为可重用函数,那么您可以执行类似于我为测试所做的操作,检查表视图是否具有五行,其中“Row 1”是可访问标签:
- (void)testThereAreThreeViewsWithRow1AsAccessibilityLabel {
NSMutableArray *evaluatedElements = [[NSMutableArray alloc] init];
__block bool considerForEvaluation = NO;
MatchesBlock matchesBlock = ^BOOL(UIView *view) {
if (considerForEvaluation) {
if (![evaluatedElements containsObject:view]) {
[evaluatedElements addObject:view];
considerForEvaluation = NO;
return YES;
}
}
return NO;
};
DescribeToBlock describeToBlock = ^void(id<GREYDescription> description) {
[description appendText:@"not in matched list"];
};
id<GREYMatcher> notAlreadyEvaluatedListMatcher =
[GREYElementMatcherBlock matcherWithMatchesBlock:matchesBlock
descriptionBlock:describeToBlock];
id<GREYMatcher> viewMatcher =
grey_allOf(grey_accessibilityLabel(@"Row 1"), notAlreadyEvaluatedListMatcher, nil);
for (int i = 0; i < 5; i++) {
considerForEvaluation = YES;
[[EarlGrey selectElementWithMatcher:viewMatcher] assertWithMatcher:grey_sufficientlyVisible()];
}
}
正如@khandpur所提到的那样,让匹配器唯一地识别一个元素确实是有意义的。但是,如果您真的不关心找到了多少个元素,我认为有一种巧妙的方法可以做到这一点。
id<GREYMatcher> matcher = grey_allOf(grey_accessibilityID(your_identifier), // or to match certain class
grey_sufficientlyVisible(),
nil);
NSError *error;
[[EarlGrey selectElementWithMatcher:matcher] assertWithMatcher:grey_isNil(!visible) error:&error];
if (!error) {
// Only one element exists
} else if ([error.domain isEqual:kGREYInteractionErrorDomain] &&
error.code == kGREYInteractionElementNotFoundErrorCode) {
// Element doesn’t exist
} else if ([error.domain isEqual:kGREYInteractionErrorDomain] &&
error.code == kGREYInteractionMultipleElementsMatchedErrorCode) {
// Multiple elements exist
// your logic ...
}