第 1 步编写一个匹配器,它可以使用以下方法计算与给定匹配器匹配GREYElementMatcherBlock
的元素:
- (NSUInteger)elementCountMatchingMatcher:(id<GREYMatcher>)matcher {
__block NSUInteger count = 0;
GREYElementMatcherBlock *countMatcher = [GREYElementMatcherBlock matcherWithMatchesBlock:^BOOL(id element) {
if ([matcher matches:element]) {
count += 1;
}
return NO; // return NO so EarlGrey continues to search.
} descriptionBlock:^(id<GREYDescription> description) {
// Pass
}];
NSError *unused;
[[EarlGrey selectElementWithMatcher:countMatcher] assertWithMatcher:grey_notNil() error:&unused];
return count;
}
步骤 2使用%
选择随机索引
NSUInteger randomIndex = arc4random() % count;
第 3 步最后使用atIndex:
选择该随机元素并对其执行操作/断言。
// Count all UIView's
NSUInteger count = [self elementCountMatchingMatcher:grey_kindOfClass([UIView class])];
// Find a random index.
NSUInteger randIndex = arc4random() % count;
// Tap the random UIView
[[[EarlGrey selectElementWithMatcher:grey_kindOfClass([UIView class])]
atIndex:randIndex]
performAction:grey_tap()];