I'm currently trying to set up a custom delegate on an async dataTaskWithRequest via NSURLSession. I've set up the protocol and implemented the delegate method, but I am stuck at figuring out whether I've implemented it correctly, and how to unit test it. Specifically, I'd like to test if the delegate returns something after it has been called, and test with a live API call. I've tried testing via the approach suggested here (OCUnit test for protocols/callbacks/delegate in Objective-C), but the test fails, probably because I'm missing something or am not taking into account the async call. Code of attempted delegate implementation and unit test are below.
Delegate protocol declaration:
#include "PtvApiPublic.h"
#ifndef PtvApiDelegate_h
#define PtvApiDelegate_h
@class PtvApi;
@protocol PtvApiDelegate <NSObject>
-(void) ptvApiHealthCheck: (PtvApi *) sender;
@end
#endif /* PtvApiDelegate_h */
Header file:
#include "PtvApiDelegate.h"
#ifndef PtvApi_h
#define PtvApi_h
@interface PtvApi : NSObject
@property (nonatomic, weak) id <NSURLSessionDelegate> delegate;
- (void)ptvApiHealthCheck;
@end
#endif /* PtvApi_h */
Snippet of PtvApi.m
#import <Foundation/Foundation.h>
#import <CommonCrypto/CommonHMAC.h>
#import <CommonCrypto/CommonDigest.h>
#import "PtvApiPublic.h"
#import "PtvApiPrivate.h"
#import "PtvApiDelegate.h"
@implementation PtvApi
@synthesize delegate;
...
- (void)ptvApiHealthCheck
{
NSString *fullUrl = [self GenerateRequestUrl];
NSURLSession *apiSession = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:delegate delegateQueue:nil];
NSURL *apiUrl = [NSURL URLWithString: fullUrl];
NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:apiUrl];
[apiSession dataTaskWithRequest:urlRequest];
}
@end
Unit test:
#import <XCTest/XCTest.h>
#import "PtvApiPublic.h"
@interface APIDelegateTests : XCTestCase <NSURLSessionDelegate>
{
PtvApi *testApi;
BOOL callbackInvoked;
}
@end
@implementation APIDelegateTests
- (void)setUp {
[super setUp];
testApi = [[PtvApi alloc] init];
testApi.delegate = self;
}
- (void)tearDown {
testApi.delegate = nil;
[super tearDown];
}
- (void)testThatApiCallbackWorks {
[testApi ptvApiHealthCheck];
XCTAssert(callbackInvoked, @"Delegate should return something, I think...");
}
@end