对于我的项目想要做一点TDD,虽然我对Objective C和单元测试很新。我创建了一个连接到Web服务的项目,该服务返回一个json响应。现在我已经创建了一个单元测试来模拟Web服务并且它一直在崩溃(甚至没有失败),而且我现在完全迷失了......
我有以下设置:
SignUpService
(创建新帐户)使用ServiceHelper
(生成实际的http网络服务请求)。像这样ServiceHelper.h
:
@protocol ServiceHelperProtocol <NSObject>
@required
- (NSString *)get:(NSString *)url;
@end
@interface ServiceHelper : NSObject <ServiceHelperProtocol> {
NSMutableData *receivedData;
}
SignUpService.h
@class ServiceHelper;
@protocol SignUpServiceProtocol <NSObject>
- (NSString *)createUserAccount:(CreateUserAccountRequest *)createUserAccountRequest;
- (bool)doesUsernameExist:(NSString *)userName;
- (BOOL)isEmailValid:(NSString *)email;
- (BOOL)doesEmailExist:(NSString *)email;
@end
@interface SignUpService : NSObject <SignUpServiceProtocol> {
id <ServiceHelperProtocol> serviceHelper;
}
@property(strong) id <ServiceHelperProtocol> serviceHelper;
- (id)initWithHelper:(id <ServiceHelperProtocol>)myServiceHelper;
接下来是单元测试(SignUpServiceTests.h和实现)
@interface SignUpServiceTests : SenTestCase {
id <NSObject, ServiceHelperProtocol> serviceHelper;
SignUpService *signUpService;
CreateUserAccountRequest *createUserAccountRequest;
}
@property(nonatomic, strong) SignUpService *signUpService;
@property(nonatomic, strong) CreateUserAccountRequest *createUserAccountRequest;
@property(nonatomic, strong) id <NSObject, ServiceHelperProtocol> serviceHelper;
实施:
@implementation SignUpServiceTests
@synthesize signUpService;
@synthesize createUserAccountRequest;
@synthesize serviceHelper;
- (void)setUp {
[super setUp];
// Set-up code here.
self.createUserAccountRequest = [[CreateUserAccountRequest alloc] init];
self.createUserAccountRequest.firstName = @"first-name";
self.createUserAccountRequest.lastName = @"last-name";
.....
self.serviceHelper = [ServiceHelper new];
self.signUpService = [[SignUpService alloc] initWithHelper:(id <ServiceHelperProtocol>) self.serviceHelper];
}
- (void)tearDown {
// Tear-down code here.
[super tearDown];
}
- (void)testOnCreateUserAccountShouldReturnCreatedUserIdWhenCorrectResponseFromService {
id mock = [OCMockObject partialMockForObject:(NSObject *) (id <ServiceHelperProtocol>) self.serviceHelper];
[[[mock stub] andReturn:@"{\"status\":\"ok\",\"create_user\":\"12\"}"] get:[OCMArg any]];
assertThat([self.signUpService createUserAccount:self.createUserAccountRequest], equalTo(@"12"));
}
该项目包含OCMock版本1.77和OCHamcrest库。
由于某种原因,测试不断崩溃“处理完成退出代码0”。当我调试时,我看不出有什么问题。我觉得它与内存管理有关,还是与OCMock和ARC有关? (如建议的here和here)
对新手Objective C开发者的任何想法或建议?
答案 0 :(得分:0)
如果没有进一步的信息,我会怀疑它不是因为内存问题而是因为加载器在启动octest时无法找到OCMock框架。在OS X中,链接器(在构建时)使用不同的方法来定位框架而不是加载器(在运行时)。
OCMock的公共版本是在加载器路径中使用@rpath构建的。这允许在运行时项目布局具有相当程度的灵活性,但最初可能会令人困惑。作为第一步,您是否可以确保将LC_RPATH环境变量设置为包含OCMock框架可用的目录?在dyld手册页上讨论@rpath有更多细节。
顺便说一下,OCMock 2.0最近发布了。