iOS 单元測试之XCTest具体解释(一)[通俗易懂]

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的project中都有一个叫做”project名Tests”的分组,这个分组里就是XCTestCase的子类。XCTest中的測试类都是继承自XCTestCase。
比如新建一个project,命名为Demo。就能看到如图
iOS 单元測试之XCTest具体解释(一)[通俗易懂]
看一下这个自己主动创建的文件中都包括了哪些内容

#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的測试用例导航

測试用例的导航如图。在測试用例的导航里,我们能够执行一组測试用例,也能够执行一个单独的測试用例
iOS 单元測试之XCTest具体解释(一)[通俗易懂]

能够鼠标右键来新建一组測试用例。
iOS 单元測试之XCTest具体解释(一)[通俗易懂]

也能够为測试用例加入失败断点来方便我们调试
iOS 单元測试之XCTest具体解释(一)[通俗易懂]


普通方法測试

比如,新建一个类命名为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小工具。


版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/116451.html原文链接:https://javaforall.net

赞 (0)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • pandas中关于DataFrame行,列显示不完全(省略)的解决办法[通俗易懂]

    pandas中关于DataFrame行,列显示不完全(省略)的解决办法[通俗易懂]有时候DataFrame中的行列数量太多,print打印出来会显示不完全。就像下图这样:列显示不全:行显示不全:添加如下代码,即可解决。#显示所有列pd.set_option(‘display.max_columns’,None)#显示所有行pd.set_option(‘display.max_rows’,None)#设置value的显示长度为100,默…

    2022年7月15日
  • qt将毫秒级时间戳转换为日期(js把对象变成字符串)

    需要加入的头文件:#include<QTime>一.秒单位时间转为字符串时、分、秒格式输出inttime_sec=100;QStringtimer=QTime(0,0,0).addSecs(int(time_sec)).toString(QString::fromLatin1(“HH:mm:ss”));qDebug()<<timer;//输出:”00:01:40″二.秒单位时间转为字符串时、分、秒、毫秒格式输出..

    2022年4月12日
  • 数据挖掘项目_数据分析师怎么自学

    数据挖掘项目_数据分析师怎么自学数据挖掘项目1.数据导入一共有4754个样本,90列的数据表格中“status”是结果标签:0表示未逾期,1表示逾期。未逾期:3561逾期:11932.数据类型分析90列中70列为float,13列为int,7列objectobject类型的列名,以及其分布3.删除无关变量4.缺失值处理5.划分数据集测试集30%,训练集70%,随机种子设置为2018待…

    2022年9月5日
  • Java教学视频下载(全集)

    Java教学视频下载(全集)1:四百本Java电子书下载链接:http://www.verycd.com/topics/2784992/2:蓝点在线Java视频教程http://you.video.sina.com.cn/a/1905723-1393828897/1/2.html3:J2EEWeb程序开发定向班V1.0Java就业班V2.0(完整版)http://www.verycd.com/topics/…

    2022年5月15日
  • vue.js对String类型转json格式及json对象转String | 详细教程,建议收藏「建议收藏」

    vue.js对String类型转json格式及json对象转String | 详细教程,建议收藏「建议收藏」vue.js对String类型转json格式及json对象转String|详细教程,建议收藏

    2022年9月18日
  • 前缀索引

    前缀索引当索引是很长的字符序列时,这个索引将会很占内存,而且会很慢,这时候就会用到前缀索引了。所谓的前缀索引就是去索引的前面几个字母作为索引,但是要降低索引的重复率,索引我们还必须要判断前缀索引的重复率。先看这样一张表:mysql&gt;select*fromtest;+———-+——-+|name|score|+——–…

    2022年5月24日

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号