Objective c 如何测试发出HTTP请求的类并在Obj-C中解析响应数据?
我有一个类需要向服务器发出HTTP请求以获取一些信息。例如:Objective c 如何测试发出HTTP请求的类并在Obj-C中解析响应数据?,objective-c,unit-testing,mocking,Objective C,Unit Testing,Mocking,我有一个类需要向服务器发出HTTP请求以获取一些信息。例如: - (NSUInteger)newsCount { NSHTTPURLResponse *response; NSError *error; NSURLRequest *request = ISKBuildRequestWithURL(ISKDesktopURL, ISKGet, cookie, nil, nil); NSData *data = [NSURLConnection sendSynchro
- (NSUInteger)newsCount {
NSHTTPURLResponse *response;
NSError *error;
NSURLRequest *request = ISKBuildRequestWithURL(ISKDesktopURL, ISKGet, cookie, nil, nil);
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
if (!data) {
NSLog(@"The user's(%@) news count could not be obtained:%@", username, [error description]);
return 0;
}
NSString *regExp = @"Usted tiene ([0-9]*) noticias? no leídas?";
NSString *stringData = [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
NSArray *match = [stringData captureComponentsMatchedByRegex:regExp];
[stringData release];
if ([match count] < 2)
return 0;
return [[match objectAtIndex:1] intValue];
}
-(整数)新闻计数{
NSHTTPURLRResponse*响应;
n错误*错误;
NSURLRequest*request=ISKBuildRequestWithURL(ISKDesktopURL,ISKGet,cookie,nil,nil);
NSData*data=[NSURLConnection sendSynchronousRequest:请求返回应答:&响应错误:&错误];
如果(!数据){
NSLog(@“无法获取用户的(%@)新闻计数:%@”,用户名,[错误说明];
返回0;
}
NSString*regExp=@“是否有任何通知?”;
NSString*stringData=[[NSString alloc]initWithData:数据编码:NSASCIIStringEncoding];
NSArray*match=[stringData captureComponentsMatchedByRegex:regExp];
[数据发布];
如果([匹配计数]<2)
返回0;
返回[[match objectAtIndex:1]intValue];
}
问题是我正在单元测试(使用OCUnit)hole框架,但问题是我需要模拟/伪造NSURLConnection的响应,以便测试不同的场景,因为我无法在服务器上测试我的框架
所以问题是,哪种方法最好?测试调用类方法(如
NSURLConnection sendSynchronousRequest)的方法总是很棘手的
以下是几个选项:
a) 用于拦截呼叫。您的单元测试将包含如下代码:
@implementation NSURLConneciton (UnitTests)
+ (NSData *)sendSynchronousRequest:(NSURLRequest *)request returningResponse:(NSURLResponse **)response error:(NSError **)error {
if (someFlagYourTestUsesToInterceptTheCall) {
// return test NSData instance
}
return invokeSupersequent(request, &response, &error);
}
@end
然后将someFlagYourTestUse设置为IntercepttheCall
,强制它拦截调用并返回测试数据
b) 另一种选择是将该调用移动到被测类中自己的方法中:
-(NSData *)retrieveNewsCount:(NSURLRequest *)request {
NSHTTPURLResponse *response;
NSError *error;
return [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
}
然后使用OCMock在测试用例中拦截该调用:
-(void)testNewsCount {
// instantiate your class
id myObject = ...;
id mock = [OCMockObject partialMockForObject:myObject];
[[[mock stub] andCall:@selector(mockNewsCount:) onObject:self] retrieveNewsCount:[OCMArg any]];
NSUInteger count = [myObject newsCount];
// validate response
...
}
// in the same test class:
-(NSData *)mockNewsCount:(NSURLRequest *)request {
// return your mock data
return mockData;
}
在本例中,OCMock的stub:andCall:onObject:someMethod
只截取对对象方法的调用,以便在测试时注入一些测试数据