· demo
这里主要测试一个登陆功能是否正常作为例子,界面很简单,先看一下演示过程。
流程1
流程2
流程3
测试样例代码
- (void)testExample { XCUIApplication *app = [[XCUIApplication alloc] init]; [app.buttons[@"点击"] tap]; XCUIElement * textFiled = [app.textFields elementMatchingType:XCUIElementTypeTextField identifier:@"test"]; [textFiled tap]; [textFiled typeText:@"user"]; XCUIElement * textFiled2 = [app.textFields elementMatchingType:XCUIElementTypeTextField identifier:@"hello"]; if ([textFiled2 exists]){ [textFiled2 tap]; [textFiled2 typeText:@"123456"]; } [app.buttons[@"点击"] tap]; } |
从上面代码不难看出,我们主要的任务就是找到某一个元素(UIButton或者UITextFiled),然后执行单击、长按、输入等操作。这里可以简单得通过app.buttons[@"点击"]获得界面上一个title为点击的按钮,或者通过elementMatchingType:identifier:来获取。经过我尝试,这个identifier的设置位置如下图
identifier
也就是说Accessibility中设置的内容都能在XCUIElement拿来利用和定位。比方设置了Accessibility中的label,就可以写一个函数遍历获取这个元素。
- (XCUIElement *)getElemWithLabel:(NSString *)str type:(XCUIElementType)type{ XCUIApplication *app = [[XCUIApplication alloc] init]; XCUIElementQuery * list = [app descendantsMatchingType:type]; for (int i = 0 ; i < list.count ; i++) { XCUIElement * tmpElem =[list elementBoundByIndex:i]; if ([tmpElem.label isEqualToString:str]) { return tmpElem; } } return nil; } |
ps:我发现elementMatchingType:identifier:中identifier如果是纯英文能拿到,但是英文加数字组合就拿不到了。。不知道算不算bug。
总结
UI Tests虽然能完成UI自动化测试,但是还仅仅是单元测试的层面,想要做到系统测试还远远不够。用来测试能不能登录可以,但是要想解决上面的支付问题还有明显的不足,比如截图,日志等(也许可以,没有深究)。
UI Tests还是在一定程度上增加了开发人员的工作,而且对开发人员有一定的技术要求。至于值不值在生产环境中使用,只能因人而异了。