我的导航栏上有一个“添加”按钮,我需要让Xcode的UI测试点击这个按钮,以便在它打开的视图控制器中执行测试。我以编程方式添加按钮,如下所示:
UIBarButtonItem *addButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(showAddVC)];
self.navigationItem.rightBarButtonItem = addButton;在我的测试中,我有:
XCUIApplication *app = [[XCUIApplication alloc] init];
XCTAssert([app.buttons[@"Add"] exists]); // <-- This passes, so the test runner does see the button.但当我尝试使用以下两种方法之一来点击它时:
// Generated using the test recorder
[app.navigationBars[@"App Title"].buttons[@"Add"] tap];或者:
// Same expression used with the XCTAsset earlier
[app.buttons[@"Add"] tap]; 什么都没发生。轻敲按钮时应该发生的操作没有发生。我试着在字里行间添加一些sleep(5)来加载应用程序,但效果不是很好。
这是测试日志:
Test Case '-[xx]' started.
t = 0.00s Start Test
t = 0.00s Set Up
2015-12-22 16:25:02.898 XCTRunner[10978:384690] Continuing to run tests in the background with task ID 1
t = 0.94s Launch xx
t = 1.01s Waiting for accessibility to load
t = 3.45s Wait for app to idle
t = 9.02s Tap "Add" Button
t = 9.02s Wait for app to idle
t = 39.07s Assertion Failure: UI Testing Failure - App failed to quiesce within 30s
xx: error: -[xx] : UI Testing Failure - App failed to quiesce within 30s发布于 2016-06-08 20:57:13
上面的答案对我来说都不起作用。经过几个小时的努力,最终让它工作的是重复敲击。试试这个:
[app.navigationBars[@"App Title"].buttons[@"Add"] tap];
[app.navigationBars[@"App Title"].buttons[@"Add"] tap];虽然上述方法最初对我有效,但我发现有时第一次敲击会起作用,这会导致两次敲击。我对此的解决方案是,在UI测试开始时,点击不触发任何操作的任意UI元素,然后照常进行。我认为第一次点击可以在某些设备上工作,或者可能在第一次UI测试运行之后。
发布于 2016-01-08 00:33:52
在您的情况下,测试exists似乎还不够。在尝试轻敲按钮之前,请等待按钮变为hittable。
expectationForPredicate(predicate, evaluatedWithObject: element, handler: nil)
waitForExpectationsWithTimeout(timeoutSeconds, handler: nil)在您的情况下,它将是:
expectationForPredicate(NSPredicate(format: "hittable == YES"), evaluatedWithObject: [app.buttons[@"Add"], handler: nil)
waitForExpectationsWithTimeout(15, handler: nil)
[app.buttons[@"Add"] tap]; 这将在waitForExpectationWithTimeout之后暂停代码的执行,直到该谓词满足给定的元素。
否则,在极端情况下,我发现在尝试与某些组件交互时有时会出现错误。这些是如何、为什么以及何时发生的,这是一个有点神秘的问题,但它们似乎与某些组件有一定的一致性,而且涉及UINavigationBars的事情似乎更经常发生。
为了克服这些问题,我发现使用这个扩展有时会起作用。
extension XCUIElement {
/* Sends a tap event to a hittable/unhittable element. Needed to get past bug */
func forceTapElement() {
if hittable {
tap()
}
else {
let coordinate: XCUICoordinate = coordinateWithNormalizedOffset(CGVectorMake(0.0, 0.0))
coordinate.tap()
}
}
}发布于 2017-09-09 15:34:12
对于那些Alex的答案不起作用的人,试试这个:
extension XCUIElement {
func forceTap() {
coordinate(withNormalizedOffset: CGVector(dx:0.5, dy:0.5)).tap()
}
}我刚刚遇到了UIWebView的问题,它是可点击的,但在通过坐标完成之前,点击是不起作用的
https://stackoverflow.com/questions/34426756
复制相似问题