一、 概述
在Xcode中新建项目的时候会默认勾选单元测试,勾选后每个XCode新建的iOS的项目中都有一个叫做”项目名Tests”的分组,这个分组里就是XCTestCase的子类,XCTest中的测试类都是继承自XCTestCase。当我们为项目增加了新的功能时,可以使用单元测试针对该模块进行测试。
二、单元测试的使用
1、 常规测试
首先新建一个名为“MyDemo”的项目,我们会看到会自动生成如下的文件:
MyDemoTests中代码为:
#import <XCTest/XCTest.h> @interface MyDemoTests : XCTestCase @end @implementationMyDemoTests - (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. // Use XCTAssert and related functions to verify your tests produce the correct results. } - (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 |
上面最重要的两个方法为setUp和tearDown,setUp方法在XCTestCase的测试方法调用之前调用。当测试全部结束之后调用tearDown方法。上面的另外两个方法是系统自动创建的功能测试用例的示例。我们可以自己创建测试方法,不过测试方法必须testXXX的格式,且不能有参数,不然不会识别为测试方法。
setUp方法可以在测试之前创建在test case方法中需要用到的一些对象等。tearDown方法则在全部的test case执行结束之后清理测试现场,释放资源删除不用的对象等。
例如,我们去除系统系统创建的两个测试用例的示例,我们自己创建一个方法:
// // MyDemoTests.m // MyDemoTests // // #import <XCTest/XCTest.h> @interface MyDemoTests : XCTestCase @end @implementationMyDemoTests - (void)setUp { [super setUp]; NSLog(@"setUp-----------------"); } - (void)tearDown { [super tearDown]; NSLog(@"tearDown-----------------"); } - (void)testMyFun{ NSLog(@"testMyFun-----------------"); } @end |
按快捷键Command + U进行单元测试,打印结果(去除了其他暂不关注的打印):
2017-03-06 15:35:35.336 MyDemo[48088:5078800] setUp-----------------
2017-03-06 15:35:35.336 MyDemo[48088:5078800] testMyFun-----------------
2017-03-06 15:35:35.337 MyDemo[48088:5078800] tearDown-----------------
接下来我们新建一个类MyClass,在MyClass中声明和实现一个getNum的方法,方法实现如下:
-(NSInteger)getNum{
return 5;
}
然后在我们MyDemoTests的testMyFun写相关单元测试代码(代码中用到了断言,断言的使用后面再讲):
// // MyDemoTests.m // MyDemoTests // // #import <XCTest/XCTest.h> #import "MyClass.h" @interface MyDemoTests : XCTestCase @end @implementationMyDemoTests - (void)setUp { [super setUp]; NSLog(@"setUp-----------------"); } - (void)tearDown { [super tearDown]; NSLog(@"tearDown-----------------"); } - (void)testMyFun{ NSLog(@"testMyFun-----------------"); MyClass *myClass = [[MyClassalloc]init]; NSIntegernum = [myClassgetNum]; XCTAssert(num < 10,@"num should less than 10"); } @end |
上面加了断言,只有当num<10的使用才能通过测试,由于此时num=5,所以可以顺利通过测试。
按快捷键Command + U进行单元测试,结果如下:
如果我们将getNum的返回结果改为15,则不会通过测试: