- (void)testExample {
// This is an example of a functional test case.
XCTAssert(YES, @"Pass");
}
XCTest中所有的测试用例的命名都是以test开头的。
普通方法测试
新建一个类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");
}
如何判断一个测试用例成功或者失败呢?XCTest使用断言来实现。
XCTAssert(expression, format...)//这是一个最基本的断言,表示如果expression满足,则测试通过,否则对应format的错误。
一些常用的断言:
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...)
性能测试
所谓性能测试,主要就是评估一段代码的运行时间,XCTest的性能的测试利用如下格式
- (void)testPerformanceExample {
// This is an example of a performance test case.
[self measureBlock:^{
// Put the code you want to measure the time of here.
}];
}
例如,我要评估一段代码,这段代码的功能是把一张图片缩小到指定的大小。
这段代码如下,这段代码我放在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");
}];
}
异步测试
异步测试的逻辑如下,首先定义一个或者多个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
}];
}
网友评论