忘れないようにメモとして記録。
テストするクラスにNSNotificationを通知する準備をする
HTTPRequest.h
#import <Foundation/Foundation.h>
/*
HTTPRequestFinishedNotification
通信終了時に発行される通知名
*/
extern NSString *const HTTPRequestFinishedNotification;
@interface HTTPRequest : NSObject
- (void)load:(void (^)(id result))completionHandler failureHandler:(void (^)(NSError *error))failureHandler;
@end
HTTPRequest.m
#import "HTTPRequest.h"
#import <AFNetworking.h>
NSString *const HTTPRequestFinishedNotification = @"HTTPRequestFinishedNotification";
@implementation HTTPRequest
- (void)load:(void (^)(id result))completionHandler failureHandler:(void (^)(NSError *error))failureHandler
{
self.completionHandler = completionHandler;
self.failureHandler = failureHandler;
self.path = @"http://wwww.hogehoge.com/test.xml";
AFHTTPRequestOperationManager *manager = [[AppManager sharedManager] HTTPRequestOperationManager];
manager.responseSerializer = [AFXMLParserResponseSerializer serializer];
manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/xml", @"text/xml", nil];
[manager GET:self.path parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];
[nc postNotificationName:HTTPRequestFinishedNotification object:nil];
self.completionHandler(responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
NSNotificationCenter *nc = [NSNotificationCenter defaultCenter];
[nc postNotificationName:HTTPRequestFinishedNotification object:nil];
self.failureHandler(error);
}];
}
@end
テストクラスのメソッドでNSNotificationの通知を受け取ってテストを実行する
SampleTest.m
- (void)testHTTPRequest
{
HTTPRequest *request = [[HTTPRequest alloc] init];
XCTestExpectation *exp = [self expectationForNotification:HTTPRequestFinishedNotification
object:nil
handler:^BOOL(NSNotification * __nonnull notification)
{
NSLog(@"%s, notification %@", __func__, notification);
[exp fulfill];
return true;
}];
[request load:^(id result) {
XCTAssertNotNil(result);
} failureHandler:^(NSError *error) {
XCTFail();
}];
[self waitForExpectationsWithTimeout:3 handler:nil];
}
こんな感じで実装すればNSNotificationを利用して、通信の完了通知を受けてから、テストを実行することができる(という理解であってる?)
非同期通信のテストってややこしい。