GHUnit test with async HTTP get action

437 Views Asked by At

I want to test async HTTP get action.

@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

I have to let _html property ?

#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

If there is more nice way, please tell me. Thank you for your kindness.

1

There are 1 best solutions below

0
On BEST ANSWER

You are doing it correct.

If you want your code to be nicer (and shorter), consider using AFNetworking and the use of blocks.

I have a GHUnit async test example, which shows nicely within 1 method.