同MSVC一样,XCode提供了丰富的程序设计功能,我们不仅可以做苹果的窗体应用程序开发,控制台程序开发,IOS开发,还能编写自定义的库文件,下面我们就来试试用XCode编写一个简单的代码库并对它进行单元测试。
首先,新建一个cocoa库项目(MyLib),记着在新建向导中勾选添加一并创建测试项目,在MyLib库里面添加两个方法(分别用于拼接字符串以及计算两个数之和)。
下面是我们的自定义库的头文件以及源码文件
//
// MyLib.h
// MyLib
//
// Created by 彭 景 on 12-7-14.
// Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//
#import <Foundation/Foundation.h>
@interface MyLib : NSObject
{
}
-(NSString *) combine:(NSString *)nstr1 With:(NSString *)nstr2;
-(int) add:(int)num1 And:(int)num2;
@end
//
// MyLib.m
// MyLib
//
// Created by 彭 景 on 12-7-14.
// Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//
#import "MyLib.h"
@implementation MyLib
-(NSString *) combine : (NSString *)nstr1 With:(NSString *)nstr2
{
NSString *res = [[NSString alloc] initWithFormat:@"%@%@",nstr1,nstr2];
return res;
}
-(int) add:(int)num1 And:(int)num2
{
return num1+num2;
}
@end
接下来修改测试项目文件
//
// MyLibTests.h
// MyLibTests
//
// Created by 彭 景 on 12-7-14.
// Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//
#import <SenTestingKit/SenTestingKit.h>
#import "MyLib.h"
@interface MyLibTests : SenTestCase
{
MyLib *mylib;
}
@end
//
// MyLibTests.m
// MyLibTests
//
// Created by 彭 景 on 12-7-14.
// Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//
#import "MyLibTests.h"
#import "MyLib.h"
@implementation MyLibTests
- (void)setUp
{
[super setUp];
// Set-up code here.
mylib = [[MyLib alloc] init];
}
- (void)tearDown
{
// Tear-down code here.
[super tearDown];
}
- (void)testExample
{
NSString *str = [NSString stringWithFormat:@"Say Goodbye"];
BOOL res = [str isEqualToString:[mylib combine:@"Say " With:@"Goodbye"]];
STAssertTrue(res,@"test one");
STAssertTrue([mylib add:3 And:4] == 6,@"test two");
//testExample (MyLibTests) failed: "[mylib add:3 And:4] == 6" should be true. test two
//STFail(@"Unit tests are not implemented yet in MyLibTests");
}
@end
运行测试项目,则会在第二个STAssertTrue函数处报错,因为3+4应该等于7而不是6。我们再通过修改自定义库文件或者测试用例来达到100%测试通过吧。
Mac下面的链接库和linux,windows平台一样的使用方便,把生成好的MyLib.dylib文件放入到我们需要添加的项目中(别弄错引用路径了),别忘了一并拷贝MyLib.h头文件过来(不然编译不通过),使用方法如下:
#import <Foundation/Foundation.h>
#import "MyLib.h"
int main (int argc, const char * argv[]) {
NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
MyLib *lib = [[MyLib alloc] init];
NSString *res = [lib combine:@"Goodmorning " With:@"teacher"];
NSLog(@"%@",res);
NSLog(@"%d",[lib add:3 And:2]);
[lib release];
[pool drain];
return 0;
}
运行程序,输出结果
2012-07-14 22:58:28.409 dbank-sdk-objc[8807:70f] Goodmorning teacher
2012-07-14 22:58:28.495 dbank-sdk-objc[8807:70f] 5