ios单元测试之XCTest

前言:测试是一个好的App不可缺少的部分。每一个App都是由一个个小的功能组合到一起的。而这些小的功能又是由一个个函数或者说算法组合到一起的。单元测试就是对这些小的功能或者函数进行测试,良好的单元测试会让代码的健壮性提高很多。XCTest就是XCode为我们提供的一个框架,它提供了各个层次的测试。

XCTestCase

每个XCode创建iOS的工程中都有一个叫做”工程名Tests”的分组,这个分组里就是XCTestCase的子类,XCTest中的测试类都是继承自XCTestCase。
例如新建一个工程,命名为Demo,就能看到如图

看一下这个自动创建的文件里都包含了哪些内容

import <UIKit/UIKit.h>

import <XCTest/XCTest.h>

@interface DemoTests : XCTestCase

@end

@implementation DemoTests

  • (void)setUp {
    [super setUp];
    // Put setup code here. This method is called before the invocation of each test method in the class.
    }

  • (void)tearDown {
    // Put teardown code here. This method is called after the invocation of each test method in the class.
    [super tearDown];
    }

  • (void)testExample {
    // This is an example of a functional test case.
    XCTAssert(YES, @"Pass");
    }

  • (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

测试用例的命名

XCTest中所有的测试用例的命名都是以test开头的。例如上文中的

  • (void)testExample {
    // This is an example of a functional test case.
    XCTAssert(YES, @"Pass");
    }

setUp和tearDown

Setup是在所有测试用例运行之前运行的函数,在这个测试用例里进行一些通用的初始化工作

tearDown是在所有的测试用例都执行完毕后执行的
XCode的测试用例导航

测试用例的导航如图,在测试用例的导航里,我们可以运行一组测试用例,也可以运行一个单独的测试用例

可以鼠标右键来新建一组测试用例。

也可以为测试用例添加失败断点来方便我们调试

查看测试结果

通过测试导航栏可以查看到测试结果

通过Report导航栏可以看到更详细的测试结果

这里写图片描述

点击测试用例后面的箭头,可以跳转到测试用例的代码。

普通方法测试

例如,新建一个类命名为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");
}

我们点击如图的左边图标单独运行这个测试用例,当然也可以在上文我提到的导航栏里单独运行。
这里写图片描述
然后会看到输出表示这个测试用例通过

Test Suite 'Selected tests' started at 2015-06-28 05:24:56 +0000
Test Suite 'DemoTests.xctest' started at 2015-06-28 05:24:56 +0000
Test Suite 'DemoTests' started at 2015-06-28 05:24:56 +0000
Test Case '-[DemoTests testModelFunc_randomLessThanTen]' started.
Test Case '-[DemoTests testModelFunc_randomLessThanTen]' passed (0.000 seconds).
Test Suite 'DemoTests' passed at 2015-06-28 05:24:56 +0000.
Executed 1 test, with 0 failures (0 unexpected) in 0.000 (0.001) seconds
Test Suite 'DemoTests.xctest' passed at 2015-06-28 05:24:56 +0000.
Executed 1 test, with 0 failures (0 unexpected) in 0.000 (0.001) seconds
Test Suite 'Selected tests' passed at 2015-06-28 05:24:56 +0000.

常用断言

如何判断一个测试用例成功或者失败呢?XCTest使用断言来实现。
最基本的断言
表示如果expression满足,则测试通过,否则对应format的错误。

XCTAssert(expression, format...)
1
还有一个用来直接Fail的断言

XCTFail(format...)
1
其他一些常用的断言:

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的性能的测试利用如下格式

对于性能测试,每一个测试用例每次会运行10次。

  • (void)testPerformanceExample {
    // This is an example of a performance test case.
    [self measureBlock:^{
    // Put the code you want to measure the time of here.
    }];
    }

例如,我要评估一段代码,循环打印NSLog 10000次。
这段代码如下,这段代码我放在UIImage的类别里。

  • (void)testPerformanceExample {
    // This is an example of a performance test case.
    [self measureBlock:^{
    for (NSInteger index = 0; index < 10000; index ++) {
    NSLog(@"%ld",index);
    }
    // Put the code you want to measure the time of here.
    }];
    }

我们都知道,测试要么成功,要么失败,那么就引入了一个关键的问题

性能测试的时候,如何判一个性能测试case是成功还是失败呢?
我们先通过上文的方式,只运行一次这个测试用例。然后看看结果和输出(这个测试用例跑的很慢,别着急)

Test Case '-[ModelTests testPerformanceExample]' failed (37.432 seconds).
Test Suite 'ModelTests' failed at 2017-02-19 09:57:26.210.
Executed 1 test, with 1 failure (0 unexpected) in 37.432 (37.433) seconds
Test Suite 'ToDoTests.xctest' failed at 2017-02-19 09:57:26.211.
Executed 1 test, with 1 failure (0 unexpected) in 37.432 (37.434) seconds
Test Suite 'Selected tests' failed at 2017-02-19 09:57:26.211.
Executed 1 test, with 1 failure (0 unexpected) in 37.432 (37.437) seconds

Test session log:
/Users/hl/Library/Developer/Xcode/DerivedData/ToDo-bbcdkwvzbmyznocgystdcavfakca/Logs/Test/98E0FA82-BACC-4361-AF39-E0734F73A545/Session-ToDoTests-2017-02-19_095641-jm2eKF.log

然后,你会发现测试失败了!这是因为我们没有给性能测试一个参考时间。
我们点击图中的的第二个叉箭头

这里写图片描述

然后,看到如图

我们来看看这几个参数都是啥意思:

Baseline 计算标准差的参考值
MAX STDD 最大允许的标准差
底部点击1,2…10可以看到每次运行的结果。
点击Edit,我们点击Average的右边的Accept,来让本次运行的平均值设置为baseline,然后然后MAX STDD改为40%。再运行这个测试用例,你会发现测试成功了。

异步测试

异步测试的逻辑如下,首先定义一个或者多个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
    }];
    }

测试结果

Test Suite 'Selected tests' started at 2015-06-28 05:49:43 +0000
Test Suite 'DemoTests.xctest' started at 2015-06-28 05:49:43 +0000
Test Suite 'DemoTests' started at 2015-06-28 05:49:43 +0000
Test Case '-[DemoTests testAsyncFunction]' started.
2015-06-28 13:49:44.920 Demo[2157:145428] Async test
Test Case '-[DemoTests testAsyncFunction]' passed (1.006 seconds).
Test Suite 'DemoTests' passed at 2015-06-28 05:49:44 +0000.
Executed 1 test, with 0 failures (0 unexpected) in 1.006 (1.007) seconds
Test Suite 'DemoTests.xctest' passed at 2015-06-28 05:49:44 +0000.
Executed 1 test, with 0 failures (0 unexpected) in 1.006 (1.009) seconds
Test Suite 'Selected tests' passed at 2015-06-28 05:49:44 +0000.

代码覆盖率

选择Target,然后选择Test模块,然后勾选Gather coverage data

然后,在report模块中,就能看到每一个.m文件的代码覆盖情况了。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 159,569评论 4 363
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,499评论 1 294
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 109,271评论 0 244
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,087评论 0 209
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,474评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,670评论 1 222
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,911评论 2 313
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,636评论 0 202
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,397评论 1 246
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,607评论 2 246
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,093评论 1 261
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,418评论 2 254
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,074评论 3 237
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,092评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,865评论 0 196
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,726评论 2 276
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,627评论 2 270

推荐阅读更多精彩内容