- (void)testExample {
// This is an example of a functional test case.
XCTAssert(YES, @"Pass");
}
XCTest中所有的測試用例的命名都是以test開頭的。
普通方法測試
新建一個(gè)類Model,有一個(gè)方法生產(chǎn)10以內(nèi)的隨機(jī)數(shù)
-(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");
}
如何判斷一個(gè)測試用例成功或者失敗呢斑鸦?XCTest使用斷言來實(shí)現(xiàn)。
XCTAssert(expression, format...)//這是一個(gè)最基本的斷言砖顷,表示如果expression滿足贰锁,則測試通過,否則對應(yīng)format的錯(cuò)誤滤蝠。
一些常用的斷言:
XCTFail(format...)
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...)
性能測試
所謂性能測試豌熄,主要就是評(píng)估一段代碼的運(yùn)行時(shí)間,XCTest的性能的測試?yán)萌缦赂袷?br>
- (void)testPerformanceExample {
// This is an example of a performance test case.
[self measureBlock:^{
// Put the code you want to measure the time of here.
}];
}
例如物咳,我要評(píng)估一段代碼锣险,這段代碼的功能是把一張圖片縮小到指定的大小。
這段代碼如下览闰,這段代碼我放在UIImage的類別里芯肤。
+ (UIImage*)imageWithImage:(UIImage*)image
scaledToSize:(CGSize)newSize
{
UIGraphicsBeginImageContext( newSize );
[image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newImage;
}
判斷resize后是否為nil,并且尺寸是否對压鉴。
- (void)testPerformanceExample {
UIImage * image = [UIImage imageNamed:@"icon.png"];
[self measureBlock:^{
UIImage * resizedImage = [UIImage imageWithImage:image scaledToSize:CGSizeMake(100, 100)];
XCTAssertNotNil(resizedImage,@"resized image should not be nil");
CGFloat resizedWidth = resizedImage.size.width;
CGFloat resizedHeight = resizedImage.size.height;
XCTAssert(resizedHeight == 100 && resizedWidth == 100,@"Size is not right");
}];
}
異步測試
異步測試的邏輯如下崖咨,首先定義一個(gè)或者多個(gè)XCTestExpectation,表示異步測試想要的結(jié)果晴弃。然后設(shè)置timeout掩幢,表示異步測試最多可以執(zhí)行的時(shí)間逊拍。最后,在異步的代碼完成的最后际邻,調(diào)用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
}];
}