使用异步HTTP获取动作的GHUnit测试

时间:2012-10-15 03:07:44

标签: objective-c unit-testing nsurlconnection gh-unit

我想测试异步HTTP get动作。

@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

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

1 个答案:

答案 0 :(得分:2)

你这样做是正确的。

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

我有一个GHUnit async test example,可以很好地显示在1个方法中。