0

我想测试异步 HTTP 获取操作。

@interface Sender : NSObject<NSURLConnectionDataDelegate, NSURLConnectionDelegate>
{
    NSMutableData       *buffer;
    NSString            *_html
}

- (void)getHtml;

@end

@implementation Sender

- (void)getHtml
{
    NSString *urlstr = @"http://www.yahoo.co.jp";
    NSURL *url = [NSURL URLWithString:urlstr];
    NSURLRequest *request = [NSURLRequest requestWithURL:url];
    NSURLConnection *conn = [NSURLConnection connectionWithRequest:request delegate:self];
    if (conn) {
        buffer = [NSMutableData data];
    } else {
        // error handling
    }
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    [buffer appendData:data];
}

-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    NSLog(@"Succeed!! Received %d bytes of data", [buffer length]);
    _html = [[NSString alloc] initWithData:buffer encoding:NSUTF8StringEncoding];
    NSLog(@"%@", _html);
}

@end

我要让_html 财产

#import "SenderTestCase.h"
#import "Sender.h"

@implementation SenderTestCase

- (void)setUpClass
{
    sender = [[Sender alloc] init];
}

- (void)testGetHtml
{
    [self prepare];
    [sender getHtml];
    [self performSelector:@selector(_succeedGetHtml) withObject:nil afterDelay:3.0];
    [self waitForStatus:kGHUnitWaitStatusSuccess timeout:4.0];
}

- (void)_succeedGetHtml
{
    if (sender.html != nil) {
        [self notify:kGHUnitWaitStatusSuccess forSelector:@selector(testGetHtml)];
    };
}

@end

如果有更好的方法,请告诉我。谢谢你的好意。

4

1 回答 1

2

你做得对。

如果您希望您的代码更好(更短),请考虑使用 AFNetworking 和使用块。

我有一个GHUnit 异步测试示例,它在 1 种方法中显示得很好。

于 2012-11-24T18:14:33.847 回答