Skip to content

Instantly share code, notes, and snippets.

@kaiinui
Last active February 10, 2016 03:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kaiinui/09e9c35ca69326c2a916 to your computer and use it in GitHub Desktop.
Save kaiinui/09e9c35ca69326c2a916 to your computer and use it in GitHub Desktop.
ObjC便利HTTPスタブクラス

OHHTTPStubs の便利ラッパークラス。

// Simulates status=200, application/json response.
[FLMHTTPStub stubURLContains:@"/books/1" withJSON:@{
                                                    @"title": @"我輩は猫である",
                                                    @"author": @"夏目漱石くん"
                                                    }];
// Simulate server down.
[FLMHTTPStub stubURLContains:@"/books/1" withHttpStatusCode:503 withJSON:nil];

Note

OHHTTPStubsはプライベートAPIを使っているのでプロダクションに含めないように注意する必要があります。 Targetをtestsだけに絞るのが一番楽ですが、もし通常のデバッグでも使いたい場合は下記のようなPodfileの書き方をします。

FLMHTTPStubはDEBUG時は何もインポートしないし、メソッドは空メソッドになるのでそのままビルドしてもproduction-readyです。

pod 'OHHTTPStubs', :configurations => ['Debug']

#import <Foundation/Foundation.h>
@interface FLMHTTPStub : NSObject
+ (void)stubURLContains:(nonnull NSString *)aStr withJSON:(nonnull NSDictionary *)json;
+ (void)stubURLContains:(nonnull NSString *)aStr withHttpStatusCode:(int)code withJSON:(nullable NSDictionary *)json;
@end
#import "FLMHTTPStub.h"
#ifdef DEBUG
#import <OHHTTPStubs.h>
#endif
@implementation FLMHTTPStub
+ (void)stubURLContains:(NSString *)aStr withJSON:(NSDictionary *)json {
#ifdef DEBUG
[OHHTTPStubs stubRequestsPassingTest:^BOOL(NSURLRequest *request) {
return [request.URL.absoluteString containsString:aStr];
} withStubResponse:^OHHTTPStubsResponse *(NSURLRequest *request) {
NSData *data = [NSJSONSerialization dataWithJSONObject:json options:NSJSONWritingPrettyPrinted error:nil];
return [OHHTTPStubsResponse responseWithData:data statusCode:200 headers:@{
@"Content-Type": @"application/json"
}];
}];
#endif
}
+ (void)stubURLContains:(NSString *)aStr withHttpStatusCode:(int)code withJSON:(NSDictionary *)json {
#ifdef DEBUG
[OHHTTPStubs stubRequestsPassingTest:^BOOL(NSURLRequest *request) {
return [request.URL.absoluteString containsString:aStr];
} withStubResponse:^OHHTTPStubsResponse *(NSURLRequest *request) {
NSDictionary *jsonOrNil = json;
if (jsonOrNil == nil) {
jsonOrNil = @{
@"message": @"Stubbed error"
};
}
NSData *data = [NSJSONSerialization dataWithJSONObject:jsonOrNil options:NSJSONWritingPrettyPrinted error:nil];
return [OHHTTPStubsResponse responseWithData:data statusCode:code headers:@{
@"Content-Type": @"application/json"
}];
}];
#endif
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment