iOS应用程序中的单元测试用例

时间:2014-05-28 09:57:01

标签: ios unit-testing

任何人都可以建议我如何使用XCTest Framework在iOS应用程序中编写单元测试用例。我可以为我在我的应用程序中编写的方法编写测试用例,但是请你建议我在调用webservices时如何编写测试用例

2 个答案:

答案 0 :(得分:1)

创建测试Web连接的方法(此测试用例只检查是否存在与This URL关联的数据)

-(void)testAPIConnection{

  // Create a flag here to check if network call is going on.
__block BOOL waitingForBlock = YES;

PListDownloader *downloader = [[PListDownloader alloc] init];

STAssertNotNil(downloader, @"Not able to create instance of downloader class");

NSURL *url = [NSURL URLWithString:@"http://www.icodeblog.com/samples/block_test/block_test.plist"];
[downloader downloadPlistForURL:url completionBlock:^(NSArray *data, NSError *error) {

    if(!error) {
        dispatch_sync(dispatch_get_main_queue(), ^(void) {

            int coutn = [data count];

            //Set the flag value NO
            waitingForBlock = NO;
            NSString *countString = [[NSString alloc]initWithFormat:@"%d",coutn];
            STAssertTrue([data count] >0, @"Should have been success!");
        });
    } else {
            STAssertTrue([data count] == 0, @"we have a failed here a number of data is 0!");
        NSLog(@"error %@", error);
    }
}];

// Wait for Flag to become True.
while(waitingForBlock) {
    [[NSRunLoop currentRunLoop] runMode:NSDefaultRunLoopMode
                             beforeDate:[NSDate dateWithTimeIntervalSinceNow:0.1]];
}

}

创建一个PListDownloader类并在.h文件中声明一个方法

- (void) downloadPlistForURL:(NSURL *) url completionBlock:(void (^)(NSArray *data, NSError *error)) block;

并在PListDownloader.m中记下使用块

下载内容的语句
- (void) downloadPlistForURL:(NSURL *) url completionBlock:(void (^)(NSArray *data, NSError *error)) block {
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0ul), ^{
    NSArray *returnArray = [NSArray arrayWithContentsOfURL:url];
    if(returnArray) {
        block(returnArray, nil);
    } else {
        NSError *error = [NSError errorWithDomain:@"plist_download_error" code:1 
                                         userInfo:[NSDictionary dictionaryWithObject:@"Can't fetch data" forKey:NSLocalizedDescriptionKey]];
        block(nil, error);
    }

});
}

答案 1 :(得分:1)

您可以等到通过同步呼叫完成Web服务呼叫,或等待一段时间进行响应。这是等待结果的例子:

// Create flag to check whether request was finished
__block BOOL isFinished = NO;

// somewhere in delegate or in competition block change value to yes, when request is finished
isFinished = YES;

// Before check result wait for it
while (!isFinished) {
  [[NSRunLoop currentRunLoop] runUntilDate:[[NSDate alloc] initWithTimeIntervalSinceNow:1]];
}

// now you can check it
XCTAssertTrue(...);

基本上,它会在isFinished == NO时循环,因此异步Web服务调用将有时间完成。循环后,您可以确定请求已完成,您可以检查结果。