我的iOS UI测试有以下测试辅助函数:
func waitForElementToHaveKeyboardFocus(element: XCUIElement) {
self.expectationForPredicate(NSPredicate(format:"valueForKey(\"hasKeyboardFocus\") == true"), evaluatedWithObject:element, handler: nil)
self.waitForExpectationsWithTimeout(5, handler: nil)
}
在我的测试中,我有:
let usernameTextField = app.textFields["Username"]
let passwordTextField = app.secureTextFields["Password"]
waitForElementToHaveKeyboardFocus(usernameTextField)
测试失败,出现以下错误:
error: -[ExampleAppUITests.ExampleAppUITests testExampleApp] : failed: caught "NSUnknownKeyException", "[<_NSPredicateUtilities 0x10e554ee8> valueForUndefinedKey:]: this class is not key value coding-compliant for the key hasKeyboardFocus."
如果我在测试中在断点处设置断点并在聚焦和未聚焦字段上手动调用valueForKey("hasKeyboardFocus")
,我似乎得到了正确的行为:
(lldb) po usernameTextField.valueForKey("hasKeyboardFocus")
t = 51.99s Find the "Username" TextField
t = 51.99s Use cached accessibility hierarchy for ExampleApp
t = 52.00s Find: Descendants matching type TextField
t = 52.01s Find: Elements matching predicate '"Username" IN identifiers'
▿ Optional<AnyObject>
- Some : 1
(lldb) po passwordTextField.valueForKey("hasKeyboardFocus")
t = 569.99s Find the "Password" SecureTextField
t = 569.99s Use cached accessibility hierarchy for ExampleApp
t = 570.01s Find: Descendants matching type SecureTextField
t = 570.01s Find: Elements matching predicate '"Password" IN identifiers'
▿ Optional<AnyObject>
- Some : 0
是否可以在valueForKey
的{{1}}中使用XCUIElement
进行UI测试?还有另一种优雅的方法吗?
答案 0 :(得分:2)
您可以执行以下操作,将valueForKey("")
的语句作为方法的闭包传递:
func waitForElementToHaveKeyboardFocus(statement statement: () -> Bool, timeoutSeconds: Int)
{
var second = 0
while statement() != true {
if second >= timeoutSeconds {
XCTFail("statement reached timeout of \(timeoutSeconds) seconds")
}
sleep(1)
second = second + 1
}
}
然后在测试中使用:
waitForElementToHaveKeyboardFocus(statement: { usernameTextField.valueForKey("hasKeyboardFocus") as? Bool == true }, timeoutSeconds: 10)
您可以将此方法重命名为更通用,它将验证传递给它的任何闭包。希望这有帮助!
答案 1 :(得分:2)
看起来您的谓词略有偏差。尝试将其更改为以下内容:
NSPredicate(format: "hasKeyboardFocus == true"), evaluatedWithObject:element, handler: nil)
创建谓词时,您不需要传递valueForKey
部分。