ios單元測試之XCTest

前言:測試是一個好的App不可缺少的部分。每一個App都是由一個個小的功能組合到一起的。而這些小的功能又是由一個個函數或者說算法組合到一起的。單元測試就是對這些小的功能或者函數進行測試,良好的單元測試會讓代碼的健壯性提高很多。XCTest就是XCode為我們提供的一個框架,它提供了各個層次的測試。

XCTestCase

每個XCode創建iOS的工程中都有一個叫做”工程名Tests”的分組,這個分組里就是XCTestCase的子類,XCTest中的測試類都是繼承自XCTestCase。
例如新建一個工程,命名為Demo,就能看到如圖

看一下這個自動創建的文件里都包含了哪些內容

import <UIKit/UIKit.h>

import <XCTest/XCTest.h>

@interface DemoTests : XCTestCase

@end

@implementation DemoTests

  • (void)setUp {
    [super setUp];
    // Put setup code here. This method is called before the invocation of each test method in the class.
    }

  • (void)tearDown {
    // Put teardown code here. This method is called after the invocation of each test method in the class.
    [super tearDown];
    }

  • (void)testExample {
    // This is an example of a functional test case.
    XCTAssert(YES, @"Pass");
    }

  • (void)testPerformanceExample {
    // This is an example of a performance test case.
    [self measureBlock:^{
    // Put the code you want to measure the time of here.
    }];
    }

@end

測試用例的命名

XCTest中所有的測試用例的命名都是以test開頭的。例如上文中的

  • (void)testExample {
    // This is an example of a functional test case.
    XCTAssert(YES, @"Pass");
    }

setUp和tearDown

Setup是在所有測試用例運行之前運行的函數,在這個測試用例里進行一些通用的初始化工作

tearDown是在所有的測試用例都執行完畢后執行的
XCode的測試用例導航

測試用例的導航如圖,在測試用例的導航里,我們可以運行一組測試用例,也可以運行一個單獨的測試用例

可以鼠標右鍵來新建一組測試用例。

也可以為測試用例添加失敗斷點來方便我們調試

查看測試結果

通過測試導航欄可以查看到測試結果

通過Report導航欄可以看到更詳細的測試結果

這里寫圖片描述

點擊測試用例后面的箭頭,可以跳轉到測試用例的代碼。

普通方法測試

例如,新建一個類命名為Model,他有這個方法用來生成10以內的隨機數。

-(NSInteger)randomLessThanTen{
return arc4random()%10;
}

于是,測試方法為

-(void)testModelFunc_randomLessThanTen{
Model * model = [[Model alloc] init];
NSInteger num = [model randomLessThanTen];
XCTAssert(num<10,@"num should less than 10");
}

我們點擊如圖的左邊圖標單獨運行這個測試用例,當然也可以在上文我提到的導航欄里單獨運行。
這里寫圖片描述
然后會看到輸出表示這個測試用例通過

Test Suite 'Selected tests' started at 2015-06-28 05:24:56 +0000
Test Suite 'DemoTests.xctest' started at 2015-06-28 05:24:56 +0000
Test Suite 'DemoTests' started at 2015-06-28 05:24:56 +0000
Test Case '-[DemoTests testModelFunc_randomLessThanTen]' started.
Test Case '-[DemoTests testModelFunc_randomLessThanTen]' passed (0.000 seconds).
Test Suite 'DemoTests' passed at 2015-06-28 05:24:56 +0000.
Executed 1 test, with 0 failures (0 unexpected) in 0.000 (0.001) seconds
Test Suite 'DemoTests.xctest' passed at 2015-06-28 05:24:56 +0000.
Executed 1 test, with 0 failures (0 unexpected) in 0.000 (0.001) seconds
Test Suite 'Selected tests' passed at 2015-06-28 05:24:56 +0000.

常用斷言

如何判斷一個測試用例成功或者失敗呢?XCTest使用斷言來實現。
最基本的斷言
表示如果expression滿足,則測試通過,否則對應format的錯誤。

XCTAssert(expression, format...)
1
還有一個用來直接Fail的斷言

XCTFail(format...)
1
其他一些常用的斷言:

XCTAssertTrue(expression, format...)
XCTAssertFalse(expression, format...)
XCTAssertEqual(expression1, expression2, format...)
XCTAssertNotEqual(expression1, expression2, format...)
XCTAssertEqualWithAccuracy(expression1, expression2, accuracy, format...)
XCTAssertNotEqualWithAccuracy(expression1, expression2, accuracy, format...)
XCTAssertNil(expression, format...)
XCTAssertNotNil(expression, format...)

性能測試

所謂性能測試,主要就是評估一段代碼的運行時間,XCTest的性能的測試利用如下格式

對于性能測試,每一個測試用例每次會運行10次。

  • (void)testPerformanceExample {
    // This is an example of a performance test case.
    [self measureBlock:^{
    // Put the code you want to measure the time of here.
    }];
    }

例如,我要評估一段代碼,循環打印NSLog 10000次。
這段代碼如下,這段代碼我放在UIImage的類別里。

  • (void)testPerformanceExample {
    // This is an example of a performance test case.
    [self measureBlock:^{
    for (NSInteger index = 0; index < 10000; index ++) {
    NSLog(@"%ld",index);
    }
    // Put the code you want to measure the time of here.
    }];
    }

我們都知道,測試要么成功,要么失敗,那么就引入了一個關鍵的問題

性能測試的時候,如何判一個性能測試case是成功還是失敗呢?
我們先通過上文的方式,只運行一次這個測試用例。然后看看結果和輸出(這個測試用例跑的很慢,別著急)

Test Case '-[ModelTests testPerformanceExample]' failed (37.432 seconds).
Test Suite 'ModelTests' failed at 2017-02-19 09:57:26.210.
Executed 1 test, with 1 failure (0 unexpected) in 37.432 (37.433) seconds
Test Suite 'ToDoTests.xctest' failed at 2017-02-19 09:57:26.211.
Executed 1 test, with 1 failure (0 unexpected) in 37.432 (37.434) seconds
Test Suite 'Selected tests' failed at 2017-02-19 09:57:26.211.
Executed 1 test, with 1 failure (0 unexpected) in 37.432 (37.437) seconds

Test session log:
/Users/hl/Library/Developer/Xcode/DerivedData/ToDo-bbcdkwvzbmyznocgystdcavfakca/Logs/Test/98E0FA82-BACC-4361-AF39-E0734F73A545/Session-ToDoTests-2017-02-19_095641-jm2eKF.log

然后,你會發現測試失敗了!這是因為我們沒有給性能測試一個參考時間。
我們點擊圖中的的第二個叉箭頭

這里寫圖片描述

然后,看到如圖

我們來看看這幾個參數都是啥意思:

Baseline 計算標準差的參考值
MAX STDD 最大允許的標準差
底部點擊1,2…10可以看到每次運行的結果。
點擊Edit,我們點擊Average的右邊的Accept,來讓本次運行的平均值設置為baseline,然后然后MAX STDD改為40%。再運行這個測試用例,你會發現測試成功了。

異步測試

異步測試的邏輯如下,首先定義一個或者多個XCTestExpectation,表示異步測試想要的結果。然后設置timeout,表示異步測試最多可以執行的時間。最后,在異步的代碼完成的最后,調用fullfill來通知異步測試滿足條件。

  • (void)testAsyncFunction{
    XCTestExpectation * expectation = [self expectationWithDescription:@"Just a demo expectation,should pass"];
    //Async function when finished call [expectation fullfill]
    [self waitForExpectationsWithTimeout:10 handler:^(NSError *error) {
    //Do something when time out
    }];
    }

舉例

  • (void)testAsyncFunction{
    XCTestExpectation * expectation = [self expectationWithDescription:@"Just a demo expectation,should pass"];
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
    sleep(1);
    NSLog(@"Async test");
    XCTAssert(YES,"should pass");
    [expectation fulfill];
    });
    [self waitForExpectationsWithTimeout:10 handler:^(NSError *error) {
    //Do something when time out
    }];
    }

測試結果

Test Suite 'Selected tests' started at 2015-06-28 05:49:43 +0000
Test Suite 'DemoTests.xctest' started at 2015-06-28 05:49:43 +0000
Test Suite 'DemoTests' started at 2015-06-28 05:49:43 +0000
Test Case '-[DemoTests testAsyncFunction]' started.
2015-06-28 13:49:44.920 Demo[2157:145428] Async test
Test Case '-[DemoTests testAsyncFunction]' passed (1.006 seconds).
Test Suite 'DemoTests' passed at 2015-06-28 05:49:44 +0000.
Executed 1 test, with 0 failures (0 unexpected) in 1.006 (1.007) seconds
Test Suite 'DemoTests.xctest' passed at 2015-06-28 05:49:44 +0000.
Executed 1 test, with 0 failures (0 unexpected) in 1.006 (1.009) seconds
Test Suite 'Selected tests' passed at 2015-06-28 05:49:44 +0000.

代碼覆蓋率

選擇Target,然后選擇Test模塊,然后勾選Gather coverage data

然后,在report模塊中,就能看到每一個.m文件的代碼覆蓋情況了。

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容