OCUnit:即XCTest,xcode自帶的測試框架。
創(chuàng)建UITest,F(xiàn)iles->new->target
導(dǎo)入:#import <XCTest/XCTest.h>
一個UITests:測試UI點(diǎn)擊、輸入事件,可以錄制操作過程。
選擇UITests類型的文件,將光標(biāo)放在自定義的測試方法中,錄制宏按鈕變成紅色,點(diǎn)擊它,程序就會自動啟動,這時候在程序中所有的操作都會生成相應(yīng)的代碼,并將代碼放到所選的測試方法體內(nèi)。
注意:錄制的代碼不一定正確,需要自己調(diào)整,
如:
app.tables.staticTexts[@"\U5bf9\U8c61”],需要將@"\U5bf9\U8c61”改成對應(yīng)的中文,不然測試運(yùn)行的時候會因匹配不了而報錯。

1)app元素概念
XCUIApplication *app = [[XCUIApplication alloc] init];
這里的app獲取的元素,都是當(dāng)前界面的元素。app將界面的元素按類型存儲,在集合中的元素,元素之間是平級關(guān)系的,按照界面順序從上往下依次排序(這點(diǎn)很重要,有時很管用);元素有子集,即如一個大的view包含了多個子控件。
常見的元素有:staticTexts(label)、textFields(輸入框)、buttons(按鈕)等等,可以查看該類文件。
在給復(fù)雜的界面錄制操作過程中,比如錄制對tableView操作,往往會出現(xiàn)錄制的代碼不管用,這就需要我們對進(jìn)行代碼進(jìn)行改寫,上面的介紹,就是很重要的認(rèn)知了。
例如:
對tableView某個cell中的textfield進(jìn)行輸入操作:
錄制的代碼:
[[[tablesQuery.cells containingType:XCUIElementTypeStaticText identifier:@"請輸入姓名"] childrenMatchingType:XCUIElementTypeTextField].element typeText:@"張三”];
//通過cell中的叫做@“請輸入姓名“的label找到這個cell的編輯框,但是往往不管用,進(jìn)行測試時通過不了。
一種正確的做法:
XCUIApplication *app = [[XCUIApplication alloc] init];
for (NSInteger i = 0;i < app.textFields.count; i++) {
if ([[app.textFields elementBoundByIndex:i] exists]) {//判斷是否存在
[[app.textFields elementBoundByIndex:i] tap];//輸入框要獲取焦點(diǎn)后才能給輸入框自動賦值
if (i == 1 || i == 3) {
continue;
}
[[app.textFields elementBoundByIndex:i] typeText:@“張三"];
}
}
po輸出所有的textfields

2)元素下面還是有元素集合
XCUIApplication* app = [[XCUIApplicationalloc] init];
//獲得當(dāng)前界面中的表視圖
XCUIElement* tableView = [app.tableselementBoundByIndex:0];
XCUIElement* cell = [tableView.cells elementBoundByIndex:0];
//元素下面還是有元素集合,如cell.staticTexts
XCTAssert(cell.staticTexts[@"Welcome"].exists);
3)界面事件
自動化測試無非就是:輸入框、label賦值,按鈕的點(diǎn)擊、雙擊,頁面的滾動等事件
//點(diǎn)擊事件tap
[app.buttons[@"確認(rèn)"] tap];
//輸入框的賦值
[[app.textFields elementBoundByIndex:i] typeText:@“張三"];
當(dāng)測試方法執(zhí)行結(jié)束后,模擬器的界面就進(jìn)入后臺了,為了不讓它進(jìn)入后臺,可以在方法結(jié)尾處下一個斷點(diǎn)。這時候的app正在運(yùn)行中,只要這個測試方法沒有結(jié)束,我們可以進(jìn)行別的操作的(不一定就要按照代碼來執(zhí)行)。
給個例子:
- (void)testAction {
XCUIApplication *app = [[XCUIApplication alloc] init];
XCUIElementQuery *tablesQuery = app.tables;
for (NSInteger i = 0;i < app.textFields.count; i++) {
if ([[app.textFields elementBoundByIndex:i] exists]) {
[[app.textFields elementBoundByIndex:i] tap];
[[app.textFields elementBoundByIndex:i] typeText:@“123456"];
}
}
//延時5秒
XCUIElement *window = [app.windows elementBoundByIndex:0];
[window pressForDuration:5];
//staticText 是沒有typeText事件的
//[[app.staticTexts elementBoundByIndex:0] typeText:@"123456"];
XCUIElement *textField = [[tablesQuery.cells containingType:XCUIElementTypeButton identifier:@"saoyisao"] childrenMatchingType:XCUIElementTypeTextField].element;
[textField tap];
[textField typeText:@"544"];
[app.buttons[@"下一步"] tap];
}