
单元测试
以测试ViewController为例。
ViewController.h文件
#import <UIKit/UIKit.h>
@interface ViewController : UIViewController
/** 逻辑测试 */
- (int)getSumWithNum1:(int)a num2:(int)b;
/** 异步测试 */
- (void)loadDataComplete:(void(^)(id info))complete;
/** 性能测试 */
- (void)openCamera;
@end
ViewController.m文件
- (int)getSumWithNum1:(int)a num2:(int)b {
return a + b;
}
- (void)loadDataComplete:(void (^)(id))complete {
dispatch_async(dispatch_get_global_queue(0, 0), ^{
sleep(2);
NSString *data = @"😝";
dispatch_async(dispatch_get_main_queue(), ^{
complete(data);
});
});
}
- (void)openCamera {
for(int i = 0; i < 1000; ++i) {
NSLog(@"这是一个字符串%d", i);
}
}
- (void)viewDidLoad {
[super viewDidLoad];
}
为了进行单元化测试,所以新建一个ViewControllerTest
文件。
步骤

- 导入测试头文件
#import "ViewController.h"
- 声明属性
@property (nonatomic, strong) ViewController *vc;
- 在
- (void)setUp;
进行初始化代码
- (void)setUp {
self.vc = [[ViewController alloc] init];
}
1、逻辑测试
- 给出测试数据
- 进行测试
- 使用断言进行判定
- (void)testSum {
// 1. given
int a = 10;
int b = 22;
// 2. when
int sum = [self.vc getSumWithNum1:a num2:b];
// 3. then
XCTAssertEqual(sum, 32, @"错误");
}
2、异步测试
- 创建
XCTestExpectation
,设置错误提示 - 调用方法,在异步中调用
fulfill
- 进行判断时间,是否在预期时间内容
XCTestExpectation *exp = [self expectationWithDescription:@"超过预期时间"];
[self.vc loadDataComplete:^(id info) {
XCTAssertNil(info, @"数据为空");
[exp fulfill];
}];
[self waitForExpectationsWithTimeout:4 handler:^(NSError * _Nullable error) {
NSLog(@"%@", error);
}];
3、性能测试

- 设置Baseline时间
- Max STDDEV 最大样本标准偏差比例
- (void)testPerformanceExample {
[self measureBlock:^{
[self.vc openCamera];
}];
}
UI测试

1、录制脚本
2、编辑脚本
3、自动化测试
获取代码覆盖率
1、点击Edit Secheme

2、选择
Test
->Options
->Code Coverage
勾起
3、运行代码查看结果

网友评论