前一篇文章里,我讲了用GHUnit写iOS单元测试,这篇主要在前一篇的基础上讲利用OCMock写单元测试,工程跟上一篇的demo同一个工程。可以从我的github下载:https://github.com/tingxuan/UnitDemo
首先讲下OCMock的背景,OCMock是一个用于建立伪造对象的简单框架,它使用Objective-C的运行时探测(Runtime introspection)功能来自动的创建对象用以代替被仿制的Objective-C类实例。其官网:http://ocmock.org/download/
言归正传,如下用OCMock写用例呢?
1、新建OCMockTest的target,如下
2、下载静态库的包,并引入到工程里的对应的OCMockTestDemo的target里,我放到了工程的Library目录
3、修改OCMockTestDemo的target的buildsettings
Tests 的 Build Setting。让 Libray Search Paths 包含 $(SRCROOT)/Libraries:
在 Header Search Paths 中增加 $(SRCROOT)/Libraries,并选中 Recursive 选择框。
修改Other linker flags
4、编码测试代码,展现层仍然继承GHTestCase
#import "GHTestCase.h"
@interface TXOCMockTestSample : GHTestCase
@end
#import "TXOCMockTestSample.h"
#import "OCMockObject.h"
#import "OCMock.h"
@implementation TXOCMockTestSample
//OCMockPass sample
- (void)testOCMockPass
{
id mock = [OCMockObject mockForClass:NSString.class];
[[[mock stub] andReturn:@"mocktest"] lowercaseString];
NSString *returnValue = [mock lowercaseString];
GHAssertEqualObjects(@"mocktest", returnValue,
@"Should have returned the expected string.");
}
- (void)testOCMockFail
{
id mock = [OCMockObject mockForClass:NSString.class];
[[[mock stub] andReturn:@"mocktest"] lowercaseString];
NSString *returnValue = [mock lowercaseString];
GHAssertEqualObjects(@"thisIsTheWrongValueToCheck",
returnValue, @"Should have returned the expected string.");
}
@end
5、修改OCMockTestDemo的main.m文件
#import <UIKit/UIKit.h>
#import "GHUnitIOS/GHUnitIOSAppDelegate.h"
#import "TXAppDelegate.h"
int main(int argc, char * argv[])
{
@autoreleasepool {
return UIApplicationMain(argc, argv, nil, NSStringFromClass([GHUnitIOSAppDelegate class]));
}
}
6、运行此target,查看效果
原文:http://blog.csdn.net/tingxuan_qhm/article/details/20307657