通常单元测试执行顺序执行后进程就退出了,对于异步函数(如:网络访问等)的测试比较麻烦。在iOS开发中可以利用Runloop来阻塞主线程,在回调函数中做断言。
代码片段如下,完整Demo
//
// SampleTest.m
// SampleTest
//
// Created by Magic Yang on 5/11/12.
// Copyright (c) 2012 Baidu. All rights reserved.
//
#import "SampleTest.h"
@implementation SampleTest
{
int statusCode;
}
- (void)setUp
{
[super setUp];
statusCode = -1;
}
- (void)tearDown
{
// Tear-down code here.
[super tearDown];
}
- (void)testExample
{
NetworkHelper *helper = [[NetworkHelper alloc] initWithDelegate:self];
[helper getStatusCodeForSite:@"http://www.baidu.com"];
NSLog(@"------------------ Waiting ------------------");
CFRunLoopRun();
STAssertTrue(statusCode == 200, @"Can not access this site");
NSLog(@"------------------ Finished ------------------");
}
- (void)succeedGotStatusCode:(int)code
{
statusCode = code;
CFRunLoopRef runLoopRef = CFRunLoopGetCurrent();
CFRunLoopStop(runLoopRef);
}
- (void)failedGotStatusCodeWithError:(NSError *)error
{
// ...
}
@end
一般单元测试执行完进程就退出,测试异步函数较麻烦。在iOS开发里,可利用Runloop阻塞主线程,在回调函数中做断言来完成异步函数测试,文中还给出了代码片段及完整Demo。
1070

被折叠的 条评论
为什么被折叠?



