I have the following code that I'm wanting to create a unit test for. I want to check if self.response is not nil
- (void)downloadJson:(NSURL *)url {
// Create a download task.
NSURLSessionDataTask *task = [[NSURLSession sharedSession]
dataTaskWithURL:url
completionHandler:^(NSData *data, NSURLResponse *response,
NSError *error) {
if (!error) {
NSError *JSONError = nil;
NSDictionary *dictionary =
[NSJSONSerialization JSONObjectWithData:data
options:0
error:&JSONError];
if (JSONError) {
NSLog(@"Serialization error: %@", JSONError.localizedDescription);
} else {
NSLog(@"Response: %@", dictionary);
self.response = dictionary;
}
} else {
NSLog(@"Error: %@", error.localizedDescription);
}
}];
// Start the task.
[task resume];
}
what I have so far is
- (void)testDownloadJson {
XCTestExpectation *expectation =
[self expectationWithDescription:@"HTTP request"];
[self.vc
downloadJson:[NSURL URLWithString:@"a json file"]];
[self waitForExpectationsWithTimeout:5
handler:^(NSError *error) {
// handler is called on _either_ success or
// failure
if (error != nil) {
XCTFail(@"timeout error: %@", error);
} else {
XCTAssertNotNil(
self.vc.response,
@"downloadJson failed to get data");
}
}];
}
But of course this isn't correct. Wondering if someone could help me get the idea on how to write this test.
Thanks