美文网首页
单元测试

单元测试

作者: 今晚月色 | 来源:发表于2019-03-27 15:57 被阅读0次
镇楼专用

单元测试

以测试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、逻辑测试

  1. 给出测试数据
  2. 进行测试
  3. 使用断言进行判定
- (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、异步测试

  1. 创建XCTestExpectation,设置错误提示
  2. 调用方法,在异步中调用fulfill
  3. 进行判断时间,是否在预期时间内容
XCTestExpectation *exp = [self expectationWithDescription:@"超过预期时间"];
[self.vc loadDataComplete:^(id info) {
    XCTAssertNil(info, @"数据为空");
    [exp fulfill];
}];
[self waitForExpectationsWithTimeout:4 handler:^(NSError * _Nullable error) {
    NSLog(@"%@", error);
}];

3、性能测试

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

UI测试

脚本录制
1、录制脚本

2、编辑脚本

3、自动化测试

获取代码覆盖率

1、点击Edit Secheme

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

相关文章

网友评论

      本文标题:单元测试

      本文链接:https://www.haomeiwen.com/subject/rdnzvqtx.html