I have a network class: iTunesAlbumDataDownloader
@implementation AlbumDataDownloader - (void)downloadDataWithURLString:(NSString *)urlString completionHandler:(void (^)(NSArray *, NSError *))completionHandler { NSURLSession *session = [NSURLSession sharedSession]; NSURLSessionDataTask *dataTask = [session dataTaskWithURL:[NSURL URLWithString:urlString] completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) { NSArray *albumsArray = [self parseJSONData:data]; completionHandler(albumsArray, error); }]; [dataTask resume]; } - (NSArray *)parseJSONData:(NSData *)data { NSMutableArray *albums = [[NSMutableArray alloc] init]; ... ...
and I need to create a Unit Test for this, which does the following:
- NSURLSessionTaskWithRequest: completeHandler data: the response is being mocked to contain fake JSON data that I have:
// Expected JSON Response
NSData *jsonResponse = [self sampleJSONData];
- The returned array from the public method downloadDataWithURLString: completeHandler: the response should contain all albums and a nil error.
Other points worth considering are that I need to make fun of NSURLSession with fake JSON "jsonResponse" data for downloadDataWithURLString: completeHandler: method WITHOUT invoking the actual network request .
I tried different things, but I just canβt fix it, I think this is a combination of falsifying a request and blocks that really confuse me.
Here are two examples of my test method that I tried (I really tried many other ways, but this is what I have left right now):
- (void)testValidJSONResponseGivesAlbumsAndNilError {
and
- (void)testValidJSONResponseGivesAlbumsAndNilError {
I have a feeling that in both cases I'm probably not familiar with :(
I would really appreciate help on this.
Thanks.
UPDATE 1:
This is what I came up with now, but I need to know if I am on the right track or still making a mistake?
id mockSession = [OCMockObject mockForClass:[NSURLSession class]]; id mockDataTask = [OCMockObject mockForClass:[NSURLSessionDataTask class]]; [[mockSession stub] dataTaskWithRequest:OCMOCK_ANY completionHandler:^(NSData _Nullable data, NSURLResponse Nullable response, NSError * Nullable error) { NSLog(@"Response: %@", response); }]; [[mockDataTask stub] andDo:^(NSInvocation *invocation) { NSLog(@"invocation: %@", invocation); }];