是一個工具.通常情況下,我們并不會用到它.
單元測試文件夾中包含一個繼承自XCTestCase的類.如下:
#import <XCTest/XCTest.h>
@interface UnitTestDemoTests : XCTestCase
@end
@implementation UnitTestDemoTests
- (void)setUp {
[super setUp];
// Put setup code here. This method is called before the invocation of each test method in the class.
//請將準備性的代碼,初始化的代碼寫在這里.這個方法在所有以Test開頭的方法之前調用
}
- (void)tearDown {
// Put teardown code here. This method is called after the invocation of each test method in the class.
// Put teardown code here.(什么是tearDown代碼?).這個方法在所有以Test開頭的方法之后調用
[super tearDown];
}
- (void)testExample {
// This is an example of a functional test case.
//這是一個功能測試的例子,
// Use XCTAssert and related functions to verify your tests produce the correct results.
//使用XCTAssert斷言和相關的函數來檢測你的測試代碼是否可以輸出正確的結果.
}
- (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
用于測試邏輯代碼的運行結果是否是準確的,是否是我們所期待的.
比如我有一個工具類,其中有一段非常核心的代碼,不希望程序運行起來測試是否有問題
#import "YFTool.h"
@implementation YFTool
/**
* 需要測試的牛逼的核心代碼,而不是通過運行整個程序來測試.
*/
+(BOOL)checkPassword:(NSInteger)password{
if (password == 123456) {
return YES;
}
return NO;
}
@end
通常并不直接在系統提供的Test文件中測試代碼,而是新建一個繼承自XCTestCase的類,在其中完成測試.比如我要測試YFTool這個類中的代碼,你需要這樣做:
#import "YFToolTest.h"
#import "YFTool.h"
@implementation YFToolTest
- (void)testCheckPassWord {
BOOL result = [YFTool checkPassword:123];
//這是一個斷言,左邊是結果表達式,如果不能獲得左邊的結果,彈出右邊的提示.
XCTAssert(result == YES,@"親,輸入的密碼有誤哦!");
}
@end
原文轉自:http://www.jianshu.com/p/fa99b9a26d0a