对于我的项目,我想做一点 TDD,尽管我对 Objective C 和单元测试还很陌生。我创建了一个连接到返回 json 响应的 Web 服务的项目。现在我创建了一个单元测试来模拟 Web 服务并且它一直在崩溃(甚至没有失败),我现在完全迷失了......
我有以下设置:
SignUpService
(创建一个新帐户)使用ServiceHelper
(发出实际的 http Web 服务请求)。像这样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 有关?(就像这里和这里建议的那样)
对新手 Objective C 开发人员有什么想法或建议吗?