告诉你什么叫单元测试?

发表于:2016-06-01来源:简书作者作者:我叫武大郎点击数: 标签:单元测试
什么是单元测试? 是一个工具.通常情况下,我们并不会用到它.

什么是单元测试?

 

是一个工具.通常情况下,我们并不会用到它.

创建一个包含单元测试的项目:

 


Snip20160508_1.png

Snip20160508_5.png


单元测试文件夹中包含一个继承自XCTestCase的类.如下:

#import <XCTest/XCTest.h>
@interface UnitTestDemoTests : XCTestCase
@end
@implementation UnitTestDemoTests
- (void)setUp {
    [super setUp];
    // Put setup code here. This method is called before the invocation of each test method in the class.
//请将准备性的代码,初始化的代码写在这里.这个方法在所有以Test开头的方法之前调用
}
- (void)tearDown {
    // Put teardown code here. This method is called after the invocation of each test method in the class.
// Put teardown code here.(什么是tearDown代码?).这个方法在所有以Test开头的方法之后调用
    [super tearDown];
}
- (void)testExample {
    // This is an example of a functional test case.
//这是一个功能测试的例子,
    // Use XCTAssert and related functions to verify your tests produce the correct results.
//使用XCTAssert断言和相关的函数来检测你的测试代码是否可以输出正确的结果.
}
- (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

单元测试有什么用?

 

用于测试逻辑代码的运行结果是否是准确的,是否是我们所期待的.

怎么用?

 

比如我有一个工具类,其中有一段非常核心的代码,不希望程序运行起来测试是否有问题

#import "YFTool.h"
@implementation YFTool
/**
 *  需要测试的牛逼的核心代码,而不是通过运行整个程序来测试.
*/
+(BOOL)checkPassword:(NSInteger)password{
    if (password == 123456) {
        return YES;
    }
    return NO;
}
@end

通常并不直接在系统提供的Test文件中测试代码,而是新建一个继承自XCTestCase的类,在其中完成测试.比如我要测试YFTool这个类中的代码,你需要这样做:


Snip20160508_9.png

单元测试的使用.

 

#import "YFToolTest.h"
#import "YFTool.h"
@implementation YFToolTest
- (void)testCheckPassWord {
    BOOL result = [YFTool checkPassword:123];
//这是一个断言,左边是结果表达式,如果不能获得左边的结果,弹出右边的提示.
    XCTAssert(result == YES,@"亲,输入的密码有误哦!");
}
@end
  • 传入123,是这样的:

    Snip20160508_11.png
  • 传入123456,是这样的:

    Snip20160508_12.png
  • 注意:
    • 测试方法一定要以test开头,Cmd + B,才会生成左侧的菱形

      Snip20160508_10.png
    • 点击菱形,运行测试代码.
    • 点击每个方法前面的菱形,测试这一个方法;点击@implementation前面的菱形,测试该类中所有的方法.

    • Snip20160508_13.png

什么时候用?

 

    • Matt哥们说,通常在需求大于一切的企业环境下面,单元测试基本上没有用武之地,但是对于如果你想要你的项目更加健壮,逻辑更加缜密,那么单元测试就是你所需要的.

原文转自:http://www.jianshu.com/p/fa99b9a26d0a