iOS 单元测试之XCTest详解(一)

原创blog,转载请注明出处

blog.csdn.net/hello_hwc

欢迎关注我的iOS-SDK详解专栏

http://blog.csdn.net/column/details/huangwenchen-ios-sdk.html



前言:测试是一个好的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的测试用例导航

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

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

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


普通方法测试

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

还有一个用来直接Fail的断言

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");
    }];
}

输出

Test Suite ‘Selected tests‘ started at 2015-06-28 05:42:39 +0000
Test Suite ‘DemoTests.xctest‘ started at 2015-06-28 05:42:39 +0000
Test Suite ‘DemoTests‘ started at 2015-06-28 05:42:39 +0000
Test Case ‘-[DemoTests testPerformanceExample]‘ started.
/Users/huangwenchen/Desktop/Demo/DemoTests/DemoTests.m:41: Test Case ‘-[DemoTests testPerformanceExample]‘ measured [Time, seconds] average: 0.000, relative standard deviation: 40.714%, values: [0.000241, 0.000116, 0.000128, 0.000089, 0.000087, 0.000081, 0.000101, 0.000093, 0.000092, 0.000087], performanceMetricID:com.apple.XCTPerformanceMetric_WallClockTime, baselineName: "", baselineAverage: , maxPercentRegression: 10.000%, maxPercentRelativeStandardDeviation: 10.000%, maxRegression: 0.100, maxStandardDeviation: 0.100
Test Case ‘-[DemoTests testPerformanceExample]‘ passed (0.357 seconds).
Test Suite ‘DemoTests‘ passed at 2015-06-28 05:42:40 +0000.
     Executed 1 test, with 0 failures (0 unexpected) in 0.357 (0.358) seconds
Test Suite ‘DemoTests.xctest‘ passed at 2015-06-28 05:42:40 +0000.
     Executed 1 test, with 0 failures (0 unexpected) in 0.357 (0.358) seconds
Test Suite ‘Selected tests‘ passed at 2015-06-28 05:42:40 +0000.
     Executed 1 test, with 0 failures (0 unexpected) in 0.357 (0.360) seconds

异步测试

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

后续:

计划下一篇会讲解Mock 测试以及一些常用的Mock小工具。


时间: 2024-08-08 11:26:38

iOS 单元测试之XCTest详解(一)的相关文章

IOS 友盟使用详解

IOS 友盟使用详解 这篇博客将会详细介绍友盟的使用,希望对博友们有所帮助. 首先我们在浏览器上搜索友盟. 在这里我们选择官网这个,进去友盟官网后我们按照下图进行选择. 接下来选择如下图 Next 这样我们便进入到了帮助文档 如果还没有友盟账号那么我们就需要注册一下了(点击图片中的注册即可) 注册成功并且登陆后我们需要按照操作获取Appkey 操作如图 NEXT 成功获取Appkey(复制下来,接下来会用到) 返回帮助文档 接下来是下载(安装)SDK,我么可以按照图片中的两种方法操作. 我选择了

ios新特征 ARC详解

IOS ARC 分类: IOS ARC2013-01-17 09:16 2069人阅读 评论(0) 收藏 举报 目录(?)[+] 关闭工程的ARC(Automatic Reference Counting) 顺带附上ARC教程 本文部分实例取自iOS 5 Toturail一书中关于ARC的教程和公开内容,仅用于技术交流和讨论.请不要将本文的部分或全部内容用于商用,谢谢合作. 欢迎转载本文,但是转载请注明本文出处:http://www.onevcat.com/2012/06/arc-hand-by

iOS定位服务编程详解

现在的移动设备很多都提供定位服务,使用iOS系统的iPhone.iPod Touch和iPad都可以提供位置服务,iOS设备能提供3种不同途径进行定位:Wifi, 蜂窝式移动电话基站, GPS卫星 iOS 不像Android系统在定位服务编程时,可以指定采用哪种途径进行定位.iOS的API把底层这些细节屏蔽掉了,开发人员和用户并不知道现在设备是采用 哪种方式进行定位的,iOS系统会根据设备的情况和周围的环境,采用一套最佳的解决方案.这个方案是这样的,如果能够接收GPS信息,那么设备优先采用 GP

iOS学习--UIScrollView 原理详解

iOS学习--UIScrollView 原理详解 http://blog.csdn.net/yanfangjin/article/details/7898189 ScrollView UIScrollView UIScrollView为了显示多于一个屏幕的内容或者超过你能放在内存中的内容. Scroll View为你处理缩小放大手势,UIScrollView实现了这些手势,并且替你处理对于它们的探测和回应.其中需要注意的子类是UITableView以及UITextView(用来显示大量的文字).

(转) IOS ASI http 框架详解

(转) IOS ASI http 框架详解 ASIHTTPRequest对CFNetwork API进行了封装,并且使用起来非常简单,用Objective-C编写,可以很好的应用在Mac OS X系统和iOS平台的应用程序中.ASIHTTPRequest适用于基本的HTTP请求,和基于REST的服务之间的交互. ASIHTTPRequest功能很强大,主要特色如下: l 通过简单的接口,即可完成向服务端提交数据和从服务端获取数据的工作 l 下载的数据,可存储到内存中或直接存储到磁盘中 l 能上传

iOS学习之UINavigationController详解与使用(二)页面切换和segmentedController

1.RootView 跳到SecondView 首先我们需要新一个View.新建SecondView,按住Command键然后按N,弹出新建页面,我们新建SecondView 2.为Button 添加点击事件,实现跳转 在RootViewController.xib中和RootViewController.h文件建立连接 在RootViewController.m中实现代码,alloc一个SecondViewController,用pushViewController到navigationCon

IOS—UITextFiled控件详解

IOS—UITextFiled控件详解 //初始化textfield并设置位置及大小 UITextField *text = [[UITextField alloc]initWithFrame:CGRectMake(20, 20, 130, 30)]; //设置边框样式,只有设置了才会显示边框样式 text.borderStyle = UITextBorderStyleRoundedRect; typedef enum { UITextBorderStyleNone, UITextBorderS

iOS学习之UINavigationController详解与使用(三)ToolBar

1.显示Toolbar  在RootViewController.m的- (void)viewDidLoad方法中添加代码,这样Toobar就显示出来了. [cpp] view plaincopyprint? [self.navigationController  setToolbarHidden:NO animated:YES]; [self.navigationController setToolbarHidden:NO animated:YES]; 2.在ToolBar上添加UIBarBu

iOS 中 NSTimer 使用详解-北京尚学堂

iOS 中 NSTimer 使用详解-北京尚学堂 前阵子在整理公司项目的时候,发现老代码在使用 NSTimer 时出现了内存泄露.然后整理了一些 NSTimer 的相关内容.比较简单,各位见笑啦. NSTimer fire 我们先用 NSTimer来做个简单的计时器,每隔5秒钟在控制台输出 Fire .比较想当然的做法是这样的: @interface DetailViewController () @property (nonatomic, weak) NSTimer *timer; @end